"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/index.ts
var index_exports = {};
__export(index_exports, {
  ChatWidget: () => ChatWidget,
  default: () => index_default,
  init: () => init
});
module.exports = __toCommonJS(index_exports);
var STORAGE_PREFIX = "chat_widget_session_";
var TYPING_PLACEHOLDER = "__cw_typing__";
var KRIYAOS_DEFAULT_API_BASE_URL = "https://agents.kriyaos.com/api/public/chat";
var DEFAULT_CHAT_ICON_URL = "https://unpkg.com/@kanhaiyamark/kriyaos-chat-widget@latest/dist/kriyaos-chat-wadget.gif";
var DEFAULT_CHAT_ICON_FALLBACK_URL = "https://app.kriyaos.com/favicon.ico";
function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}
function rgbToHex(r, g, b) {
  return "#" + [r, g, b].map((x) => {
    const hex = x.toString(16);
    return hex.length === 1 ? "0" + hex : hex;
  }).join("");
}
function lightenColor(hex, percent) {
  const rgb = hexToRgb(hex);
  if (!rgb) return hex;
  const r = Math.round(rgb.r + (255 - rgb.r) * (percent / 100));
  const g = Math.round(rgb.g + (255 - rgb.g) * (percent / 100));
  const b = Math.round(rgb.b + (255 - rgb.b) * (percent / 100));
  return rgbToHex(r, g, b);
}
function darkenColor(hex, percent) {
  const rgb = hexToRgb(hex);
  if (!rgb) return hex;
  const r = Math.round(rgb.r * (1 - percent / 100));
  const g = Math.round(rgb.g * (1 - percent / 100));
  const b = Math.round(rgb.b * (1 - percent / 100));
  return rgbToHex(r, g, b);
}
function isGradient(color) {
  return color.includes("linear-gradient") || color.includes("radial-gradient");
}
function getAlphaColor(color, alpha) {
  if (isGradient(color)) return color;
  const hex = color.startsWith("#") ? color : "#000000";
  const alpha_hex = Math.round(alpha * 255).toString(16).padStart(2, "0");
  return hex + alpha_hex;
}
function getFontSizeMultiplier(mode) {
  switch (mode) {
    case "small":
      return 0.85;
    case "large":
      return 1.2;
    case "medium":
    default:
      return 1;
  }
}
function style(themeColor, fontSizeMode) {
  const mult = getFontSizeMultiplier(fontSizeMode);
  const fs = {
    toggle: Math.round(28 * mult),
    logo: Math.round(15 * mult),
    title: Math.round(18 * mult),
    status: Math.round(12 * mult),
    message: Math.round(15 * mult),
    quick: Math.round(13 * mult),
    input: Math.round(14 * mult),
    brand: Math.round(11 * mult)
  };
  let colorDarker = themeColor;
  let colorAlpha = themeColor + "33";
  if (!isGradient(themeColor)) {
    colorDarker = darkenColor(themeColor, 15);
    colorAlpha = getAlphaColor(themeColor, 0.2);
  }
  return `
  .cw-root * { box-sizing: border-box; font-family: 'Segoe UI', sans-serif; }
  .cw-toggle {
    position: fixed;
    right: 20px;
    bottom: 20px;
    width: 66px;
    height: 66px;
    border-radius: 50%;
    border: 3px solid rgba(255, 255, 255, 0.3);
    color: #fff;
    background: ${themeColor};
    cursor: pointer;
    box-shadow: 
      0 0 20px ${colorAlpha},
      0 8px 32px rgba(0, 0, 0, 0.4),
      0 0 40px ${!isGradient(themeColor) ? lightenColor(themeColor, 30) + "66" : "rgba(30, 99, 255, 0.4)"},
      inset 0 0 20px rgba(255, 255, 255, 0.2);
    z-index: 999999;
    padding: 0;
    overflow: hidden;
    display: grid;
    place-items: center;
    transition: all 300ms ease;
    filter: drop-shadow(0 0 15px ${colorAlpha});
  }
  .cw-toggle:hover {
    cursor: pointer;
    transform: scale(1.1);
    box-shadow: 
      0 0 30px ${colorAlpha},
      0 12px 40px rgba(0, 0, 0, 0.5),
      0 0 50px ${!isGradient(themeColor) ? lightenColor(themeColor, 20) + "88" : "rgba(30, 99, 255, 0.6)"},
      inset 0 0 25px rgba(255, 255, 255, 0.3);
    filter: drop-shadow(0 0 25px ${colorAlpha});
  }
  .cw-toggle:active {
    transform: scale(0.98);
  }
  .cw-toggle-inner {
    position: relative;
    width: 100%;
    height: 100%;
    display: grid;
    place-items: center;
  }
  .cw-toggle-icon {
    width: ${Math.round(36 * mult)}px;
    height: ${Math.round(36 * mult)}px;
    display: block;
    animation: cw-float 2.8s ease-in-out infinite;
  }
  .cw-toggle-badge {
    position: absolute;
    top: -6px;
    right: -6px;
    min-width: 28px;
    height: 20px;
    padding: 0 8px;
    border-radius: 999px;
    background: linear-gradient(135deg, #4fe9ff, #00d4ff);
    color: #071433;
    font-size: ${Math.max(11, Math.round(fs.status + 1))}px;
    font-weight: 900;
    letter-spacing: 0.02em;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    box-shadow: 
      0 0 15px rgba(79, 233, 255, 0.8),
      0 8px 20px rgba(79, 233, 255, 0.5),
      0 0 25px rgba(0, 212, 255, 0.4);
    animation: cw-badge-pulse 2.8s ease-in-out infinite;
    border: 2px solid rgba(255, 255, 255, 0.5);
  }
  .cw-toggle-badge::after {
    content: "";
    position: absolute;
    left: 10px;
    bottom: -5px;
    width: 9px;
    height: 9px;
    background: #4fe9ff;
    clip-path: polygon(0 0, 100% 0, 0 100%);
    transform: rotate(-45deg);
  }
  .cw-toggle svg {
    width: 100%;
    height: 100%;
  }
  .cw-toggle img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    display: block;
  }
  .cw-panel {
    position: fixed;
    right: 20px;
    bottom: 88px;
    width: min(360px, calc(100vw - 24px));
    height: 520px;
    background: #f5f7fb;
    border: 1px solid #dbe3ee;
    border-radius: 22px;
    box-shadow: 0 20px 50px rgba(15, 23, 42, 0.22);
    z-index: 999999;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .cw-hidden { display: none; }
  .cw-head {
    background: #ffffff;
    border-bottom: 1px solid #e5ebf3;
    padding: 14px 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
  }
  .cw-head-actions {
    display: inline-flex;
    align-items: center;
    gap: 8px;
  }
  .cw-clear {
    border: 1px solid #e4e9f1;
    background: #f8fafc;
    color: #475467;
    border-radius: 10px;
    padding: 6px 10px;
    font-size: ${Math.max(11, Math.round(fs.status))}px;
    font-weight: 600;
    cursor: pointer;
    transition: background 160ms ease, border-color 160ms ease, color 160ms ease;
  }
  .cw-clear:hover {
    background: #ffffff;
    border-color: #d0d8e5;
    color: #1f2937;
  }
  .cw-head-left {
    display: flex;
    align-items: center;
    gap: 12px;
    min-width: 0;
  }
  .cw-logo {
    width: 42px;
    height: 42px;
    border-radius: 50%;
    background: linear-gradient(135deg, ${themeColor}, ${colorDarker});
    overflow: hidden;
    display: grid;
    place-items: center;
    font-size: ${fs.logo}px;
    color: #fff;
    font-weight: 700;
    box-shadow: 0 8px 18px ${colorAlpha};
  }
  .cw-logo img { width: 100%; height: 100%; object-fit: cover; }
  .cw-title-wrap { min-width: 0; }
  .cw-title {
    font-size: ${fs.title}px;
    font-weight: 800;
    line-height: 1.1;
    color: #101828;
  }
  .cw-status {
    margin-top: 2px;
    font-size: ${fs.status}px;
    color: #98a2b3;
    display: flex;
    align-items: center;
    gap: 6px;
  }
  .cw-status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #22c55e;
    box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.15);
  }
  .cw-close {
    border: none;
    background: transparent;
    color: #667085;
    font-size: 28px;
    line-height: 1;
    cursor: pointer;
    padding: 0 4px;
  }
  .cw-close:hover { color: #111827; }
  .cw-body {
    padding: 14px;
    flex: 1;
    overflow-y: auto;
    background: #eef2f6;
    display: flex;
    flex-direction: column;
    gap: 10px;
    scrollbar-width: thin;
    scrollbar-color: #b8c3d8 transparent;
  }
  .cw-body::-webkit-scrollbar {
    width: 8px;
  }
  .cw-body::-webkit-scrollbar-track {
    background: transparent;
  }
  .cw-body::-webkit-scrollbar-thumb {
    background: #b8c3d8;
    border-radius: 999px;
    border: 2px solid #eef2f6;
  }
  .cw-body::-webkit-scrollbar-thumb:hover {
    background: #9ba9c2;
  }
  .cw-msg {
    max-width: 85%;
    padding: 11px 13px;
    border-radius: 16px;
    white-space: pre-wrap;
    font-size: ${fs.message}px;
    line-height: 1.35;
    word-break: break-word;
    animation: cw-msg-in 220ms ease;
  }
  .cw-msg-user {
    align-self: flex-end;
    background: linear-gradient(135deg, ${themeColor}, ${colorDarker});
    color: #fff;
    border-bottom-right-radius: 8px;
    box-shadow: 0 8px 20px ${colorAlpha};
  }
  .cw-msg-assistant {
    align-self: flex-start;
    background: #ffffff;
    color: #1f2937;
    border: 1px solid #e4e9f1;
    border-bottom-left-radius: 8px;
  }
  .cw-quick {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 2px;
    margin-bottom: 6px;
  }
  .cw-quick-btn {
    border: 1px solid ${!isGradient(themeColor) ? lightenColor(themeColor, 50) : "#b9ccf7"};
    border-radius: 999px;
    background: ${!isGradient(themeColor) ? lightenColor(themeColor, 90) : "#f8fbff"};
    color: ${!isGradient(themeColor) ? themeColor : "#1e63ff"};
    font-size: ${fs.quick}px;
    font-weight: 600;
    padding: 6px 12px;
    cursor: pointer;
    transition: background 160ms ease, border-color 160ms ease, transform 160ms ease;
  }
  .cw-quick-btn:hover {
    background: ${!isGradient(themeColor) ? lightenColor(themeColor, 80) : "#eef5ff"};
    border-color: ${!isGradient(themeColor) ? lightenColor(themeColor, 40) : "#92b2f3"};
    transform: translateY(-1px);
  }
  .cw-input-wrap {
    border-top: 1px solid #e9edf3;
    display: flex;
    gap: 8px;
    padding: 10px 12px;
    background: #ffffff;
  }
  .cw-input {
    flex: 1;
    border: 1px solid ${!isGradient(themeColor) ? lightenColor(themeColor, 60) : "#cfd9e8"};
    border-radius: 12px;
    padding: 11px 12px;
    font-size: ${fs.input}px;
    color: #111827;
    caret-color: ${!isGradient(themeColor) ? themeColor : "#1e63ff"};
    outline: none;
    background: #f8fafc;
  }
  .cw-input::placeholder {
    color: #98a2b3;
    opacity: 1;
  }
  .cw-input:focus { border-color: ${!isGradient(themeColor) ? lightenColor(themeColor, 50) : "#98b3e9"}; background: #fff; }
  .cw-send {
    border: none;
    border-radius: 12px;
    background: linear-gradient(135deg, ${themeColor}, ${colorDarker});
    color: white;
    min-width: 78px;
    padding: 10px 14px;
    cursor: pointer;
    font-weight: 700;
    transition: transform 180ms ease, box-shadow 180ms ease;
  }
  .cw-send:hover:not([disabled]) {
    transform: translateY(-1px);
    box-shadow: 0 10px 22px ${colorAlpha};
  }
  .cw-send[disabled] { opacity: 0.6; cursor: not-allowed; }
  .cw-msg-loading {
    min-width: 72px;
    padding: 10px 12px;
  }
  .cw-wave {
    display: inline-flex;
    align-items: flex-end;
    gap: 5px;
    height: 12px;
  }
  .cw-wave-dot {
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background: linear-gradient(135deg, ${themeColor}, ${colorDarker});
    opacity: 0.45;
    animation: cw-wave 900ms ease-in-out infinite;
  }
  .cw-wave-dot-2 { animation-delay: 120ms; }
  .cw-wave-dot-3 { animation-delay: 240ms; }
  @keyframes cw-wave {
    0%, 100% { transform: translateY(1px); opacity: 0.35; }
    50% { transform: translateY(-3px); opacity: 1; }
  }
  @keyframes cw-msg-in {
    from { opacity: 0; transform: translateY(6px) scale(0.99); }
    to { opacity: 1; transform: translateY(0) scale(1); }
  }
  @keyframes cw-float {
    0%, 100% { transform: translateY(0) scale(1); }
    50% { transform: translateY(-4px) scale(1.02); }
  }
  @keyframes cw-badge-pulse {
    0%, 100% { transform: translateY(0) scale(1); box-shadow: 0 0 15px rgba(79, 233, 255, 0.8), 0 8px 20px rgba(79, 233, 255, 0.5), 0 0 25px rgba(0, 212, 255, 0.4); }
    50% { transform: translateY(-2px) scale(1.15); box-shadow: 0 0 25px rgba(79, 233, 255, 1), 0 12px 28px rgba(79, 233, 255, 0.8), 0 0 35px rgba(0, 212, 255, 0.6); }
  }
  .cw-brand {
    border-top: 1px solid #e6ecf5;
    padding: 7px 10px;
    background: #ffffff;
    color: #6b7280;
    display: flex;
    justify-content: center;
  }
  .cw-brand-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 10px;
    border-radius: 999px;
    border: 1px solid #eceff4;
    background: linear-gradient(180deg, #ffffff, #f8fafc);
    font-size: ${fs.brand}px;
    letter-spacing: 0.01em;
    color: #111827;
  }
  .cw-brand-logo {
    width: 16px;
    height: 16px;
    object-fit: contain;
    border-radius: 4px;
    display: inline-block;
  }
  .cw-brand-label {
    color: #6b7280;
    font-weight: 500;
  }
  .cw-brand-link {
    color: #111827;
    text-decoration: none;
    font-weight: 800;
  }
  .cw-brand-link:hover { text-decoration: underline; color: #000000; }
  @media (max-width: 640px) {
    .cw-panel { right: 12px; left: 12px; width: auto; }
  }
  `;
}
var ChatWidgetRuntime = class {
  config;
  messages = [];
  sessionId;
  resolvedApiUrl;
  root;
  bodyEl;
  panelEl;
  inputEl;
  sendEl;
  clearEl;
  getQuickActions() {
    return this.config.quickActions || [
      "Build AI chatbot",
      "Using ChatBot",
      "I have questions",
      "Just browsing"
    ];
  }
  constructor(config) {
    this.config = config;
    this.resolvedApiUrl = this.resolveApiUrl();
    const sid = localStorage.getItem(this.storageKey("sessionId"));
    this.sessionId = sid || null;
    if (this.sessionId) {
      this.setSessionId(this.sessionId);
    }
  }
  setSessionId(id) {
    this.sessionId = id;
    localStorage.setItem(this.storageKey("sessionId"), id);
  }
  clearSessionId() {
    this.sessionId = null;
    localStorage.removeItem(this.storageKey("sessionId"));
  }
  resolveApiUrl() {
    const { workspaceId, agentId } = this.config;
    const base = this.config.apiBaseUrl || KRIYAOS_DEFAULT_API_BASE_URL;
    const separator = base.includes("?") ? "&" : "?";
    const withIds = `${base}${separator}workspaceId=${encodeURIComponent(workspaceId)}&agentId=${encodeURIComponent(agentId)}`;
    if (/[?&]stream=/.test(withIds)) {
      return withIds;
    }
    return `${withIds}&stream=true`;
  }
  storageKey(suffix) {
    const keySeed = this.config.storageKey || `${this.config.workspaceId}_${this.config.agentId}`;
    const safeKey = keySeed.replace(/[^a-zA-Z0-9]/g, "_").slice(-60);
    return `${STORAGE_PREFIX}${safeKey}_${suffix}`;
  }
  init() {
    this.mount();
    this.loadMessages();
    if (!this.messages.length) {
      this.addMessage({
        id: crypto.randomUUID(),
        role: "assistant",
        text: this.config.theme?.welcomeMessage || "Hello! Ask me anything.",
        ts: Date.now()
      });
    }
    this.renderMessages();
  }
  mount() {
    const primary = this.config.theme?.primaryColor || "#1e63ff";
    const fontSizeMode = this.config.theme?.fontSizeMode || "medium";
    this.root = document.createElement("div");
    this.root.className = "cw-root";
    const styleTag = document.createElement("style");
    styleTag.textContent = style(primary, fontSizeMode);
    const toggle = document.createElement("button");
    toggle.className = "cw-toggle";
    toggle.type = "button";
    toggle.setAttribute("aria-label", "Open chat");
    const toggleInner = document.createElement("span");
    toggleInner.className = "cw-toggle-inner";
    const toggleIcon = document.createElement("img");
    toggleIcon.src = this.config.theme?.logoUrl || DEFAULT_CHAT_ICON_URL;
    toggleIcon.alt = "Chat icon";
    toggleIcon.addEventListener("error", () => {
      if (toggleIcon.src !== DEFAULT_CHAT_ICON_FALLBACK_URL) {
        toggleIcon.src = DEFAULT_CHAT_ICON_FALLBACK_URL;
      }
    });
    const toggleBadge = document.createElement("span");
    toggleBadge.className = "cw-toggle-badge";
    toggleBadge.textContent = "Hi";
    toggleInner.appendChild(toggleIcon);
    toggleInner.appendChild(toggleBadge);
    toggle.appendChild(toggleInner);
    this.panelEl = document.createElement("div");
    this.panelEl.className = "cw-panel cw-hidden";
    const head = document.createElement("div");
    head.className = "cw-head";
    const headLeft = document.createElement("div");
    headLeft.className = "cw-head-left";
    const logoWrap = document.createElement("div");
    logoWrap.className = "cw-logo";
    if (this.config.theme?.logoUrl) {
      const img = document.createElement("img");
      img.src = this.config.theme.logoUrl;
      img.alt = "logo";
      logoWrap.appendChild(img);
    } else {
      const fallbackIcon = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      fallbackIcon.setAttribute("viewBox", "0 0 24 24");
      fallbackIcon.setAttribute("fill", "none");
      fallbackIcon.setAttribute("stroke", "currentColor");
      fallbackIcon.setAttribute("stroke-width", "1.9");
      fallbackIcon.setAttribute("stroke-linecap", "round");
      fallbackIcon.setAttribute("stroke-linejoin", "round");
      fallbackIcon.setAttribute("aria-hidden", "true");
      const fallbackBubble = document.createElementNS("http://www.w3.org/2000/svg", "path");
      fallbackBubble.setAttribute("d", "M20 14.5A6.5 6.5 0 0 1 13.5 21H9l-4 3v-4.1A6.5 6.5 0 0 1 4 14.5v-4A6.5 6.5 0 0 1 10.5 4h3A6.5 6.5 0 0 1 20 10.5z");
      const fallbackEyeLine = document.createElementNS("http://www.w3.org/2000/svg", "path");
      fallbackEyeLine.setAttribute("d", "M8.5 11.2h7");
      const fallbackMouthLine = document.createElementNS("http://www.w3.org/2000/svg", "path");
      fallbackMouthLine.setAttribute("d", "M8.5 8.9h4.6");
      fallbackIcon.appendChild(fallbackBubble);
      fallbackIcon.appendChild(fallbackEyeLine);
      fallbackIcon.appendChild(fallbackMouthLine);
      logoWrap.appendChild(fallbackIcon);
    }
    const titleWrap = document.createElement("div");
    titleWrap.className = "cw-title-wrap";
    const title = document.createElement("div");
    title.className = "cw-title";
    title.textContent = this.config.title || "ChatBot";
    const status = document.createElement("div");
    status.className = "cw-status";
    const statusDot = document.createElement("span");
    statusDot.className = "cw-status-dot";
    const statusText = document.createElement("span");
    statusText.textContent = "Online";
    status.appendChild(statusDot);
    status.appendChild(statusText);
    titleWrap.appendChild(title);
    titleWrap.appendChild(status);
    const close = document.createElement("button");
    close.className = "cw-close";
    close.setAttribute("aria-label", "Close chat");
    close.textContent = "\xD7";
    const clear = document.createElement("button");
    clear.className = "cw-clear";
    clear.type = "button";
    clear.setAttribute("aria-label", "Clear chat");
    clear.textContent = "Clear";
    this.clearEl = clear;
    this.bodyEl = document.createElement("div");
    this.bodyEl.className = "cw-body";
    const inputWrap = document.createElement("div");
    inputWrap.className = "cw-input-wrap";
    this.inputEl = document.createElement("input");
    this.inputEl.className = "cw-input";
    this.inputEl.placeholder = "Type your message...";
    this.inputEl.spellcheck = false;
    this.sendEl = document.createElement("button");
    this.sendEl.className = "cw-send";
    this.sendEl.textContent = "Send";
    const branding = document.createElement("div");
    branding.className = "cw-brand";
    const brandBadge = document.createElement("div");
    brandBadge.className = "cw-brand-badge";
    const brandLogo = document.createElement("img");
    brandLogo.className = "cw-brand-logo";
    brandLogo.src = "https://app.kriyaos.com/favicon.ico";
    brandLogo.alt = "KriyaOS logo";
    brandLogo.loading = "lazy";
    const brandLabel = document.createElement("span");
    brandLabel.className = "cw-brand-label";
    brandLabel.textContent = "Powered by";
    const brandLink = document.createElement("a");
    brandLink.className = "cw-brand-link";
    brandLink.href = "https://www.kriyaos.com/";
    brandLink.target = "_blank";
    brandLink.rel = "noopener noreferrer";
    brandLink.textContent = "KriyaOS";
    brandBadge.appendChild(brandLogo);
    brandBadge.appendChild(brandLabel);
    brandBadge.appendChild(brandLink);
    branding.appendChild(brandBadge);
    headLeft.appendChild(logoWrap);
    headLeft.appendChild(titleWrap);
    const headActions = document.createElement("div");
    headActions.className = "cw-head-actions";
    headActions.appendChild(clear);
    headActions.appendChild(close);
    head.appendChild(headLeft);
    head.appendChild(headActions);
    inputWrap.appendChild(this.inputEl);
    inputWrap.appendChild(this.sendEl);
    this.panelEl.appendChild(head);
    this.panelEl.appendChild(this.bodyEl);
    this.panelEl.appendChild(inputWrap);
    this.panelEl.appendChild(branding);
    this.root.appendChild(styleTag);
    this.root.appendChild(toggle);
    this.root.appendChild(this.panelEl);
    document.body.appendChild(this.root);
    toggle.addEventListener("click", () => {
      this.panelEl.classList.toggle("cw-hidden");
    });
    close.addEventListener("click", () => {
      this.panelEl.classList.add("cw-hidden");
    });
    this.clearEl.addEventListener("click", () => {
      this.clearChat();
    });
    this.sendEl.addEventListener("click", () => {
      void this.sendMessage();
    });
    this.inputEl.addEventListener("keydown", (e) => {
      if (e.key === "Enter") {
        e.preventDefault();
        void this.sendMessage();
      }
    });
  }
  loadMessages() {
    const raw = localStorage.getItem(this.storageKey("messages"));
    if (!raw) return;
    try {
      this.messages = JSON.parse(raw).filter((msg) => msg.text !== TYPING_PLACEHOLDER);
    } catch {
      this.messages = [];
    }
  }
  persistMessages() {
    localStorage.setItem(this.storageKey("messages"), JSON.stringify(this.messages.slice(-100)));
  }
  scrollToBottom(smooth = false) {
    this.bodyEl.scrollTo({
      top: this.bodyEl.scrollHeight,
      behavior: smooth ? "smooth" : "auto"
    });
  }
  addMessage(msg) {
    this.messages.push(msg);
    this.persistMessages();
  }
  renderMessages() {
    this.bodyEl.innerHTML = "";
    if (this.messages.length <= 1) {
      const quickWrap = document.createElement("div");
      quickWrap.className = "cw-quick";
      this.getQuickActions().forEach((label) => {
        const quickButton = document.createElement("button");
        quickButton.className = "cw-quick-btn";
        quickButton.type = "button";
        quickButton.textContent = label;
        quickButton.addEventListener("click", () => {
          this.inputEl.value = label;
          void this.sendMessage();
        });
        quickWrap.appendChild(quickButton);
      });
      this.bodyEl.appendChild(quickWrap);
    }
    this.messages.forEach((m) => {
      const bubble = document.createElement("div");
      bubble.className = `cw-msg ${m.role === "user" ? "cw-msg-user" : "cw-msg-assistant"}`;
      if (m.text === TYPING_PLACEHOLDER) {
        bubble.classList.add("cw-msg-loading");
        const wave = document.createElement("div");
        wave.className = "cw-wave";
        const dot1 = document.createElement("span");
        dot1.className = "cw-wave-dot";
        const dot2 = document.createElement("span");
        dot2.className = "cw-wave-dot cw-wave-dot-2";
        const dot3 = document.createElement("span");
        dot3.className = "cw-wave-dot cw-wave-dot-3";
        wave.appendChild(dot1);
        wave.appendChild(dot2);
        wave.appendChild(dot3);
        bubble.appendChild(wave);
      } else {
        bubble.textContent = m.text;
      }
      this.bodyEl.appendChild(bubble);
    });
    this.scrollToBottom();
  }
  updateLastBubbleText(text, smoothScroll = false) {
    const bubbles = this.bodyEl.querySelectorAll(".cw-msg");
    const lastBubble = bubbles[bubbles.length - 1];
    if (!lastBubble) {
      this.renderMessages();
      return;
    }
    lastBubble.classList.remove("cw-msg-loading");
    lastBubble.textContent = text;
    this.scrollToBottom(smoothScroll);
  }
  clearChat() {
    this.messages = [];
    localStorage.removeItem(this.storageKey("messages"));
    this.clearSessionId();
    this.addMessage({
      id: crypto.randomUUID(),
      role: "assistant",
      text: this.config.theme?.welcomeMessage || "Hello! Ask me anything.",
      ts: Date.now()
    });
    this.renderMessages();
  }
  transformKriyaosResponse(data) {
    const kriyaosData = data;
    const reply = kriyaosData.message?.parts?.find((part) => part.type === "text")?.text || "No reply returned by API.";
    return {
      reply,
      sessionId: kriyaosData.session?.id || kriyaosData.id || kriyaosData.messageMetadata?.sessionId || null
    };
  }
  async sendMessage() {
    const text = this.inputEl.value.trim();
    if (!text) return;
    this.inputEl.value = "";
    this.sendEl.disabled = true;
    this.addMessage({
      id: crypto.randomUUID(),
      role: "user",
      text,
      ts: Date.now()
    });
    this.renderMessages();
    const typingId = crypto.randomUUID();
    this.addMessage({ id: typingId, role: "assistant", text: TYPING_PLACEHOLDER, ts: Date.now() });
    this.renderMessages();
    try {
      const requestPayload = this.sessionId ? {
        id: this.sessionId,
        messages: [
          {
            role: "user",
            parts: [{ type: "text", text }]
          }
        ]
      } : {
        messages: [
          {
            role: "user",
            parts: [{ type: "text", text }]
          }
        ]
      };
      const res = await fetch(this.resolvedApiUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...this.config.headers || {}
        },
        body: JSON.stringify(requestPayload)
      });
      if (!res.ok) {
        throw new Error(`Request failed with status ${res.status}`);
      }
      const contentType = res.headers.get("content-type") || "";
      if (contentType.includes("text/event-stream")) {
        this.messages = this.messages.filter((m) => m.id !== typingId);
        this.addMessage({ id: crypto.randomUUID(), role: "assistant", text: "", ts: Date.now() });
        this.renderMessages();
        await this.handleStreamingResponse(res);
      } else {
        const data = await res.json();
        const transformed = this.transformKriyaosResponse(data);
        const reply = transformed.reply;
        if (transformed.sessionId) {
          this.setSessionId(transformed.sessionId);
        }
        this.messages = this.messages.filter((m) => m.id !== typingId);
        this.addMessage({ id: crypto.randomUUID(), role: "assistant", text: "", ts: Date.now() });
        await this.animateAssistantText(reply || "No reply returned by API.");
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "";
      const isCorsLikeError = /failed to fetch|networkerror|cors/i.test(errorMessage);
      this.messages = this.messages.filter((m) => m.id !== typingId);
      this.addMessage({
        id: crypto.randomUUID(),
        role: "assistant",
        text: isCorsLikeError ? "Connection blocked by CORS. Please allow this website origin in your Kriyaos agent API settings." : "Something went wrong. Please try again.",
        ts: Date.now()
      });
    } finally {
      this.sendEl.disabled = false;
      this.renderMessages();
    }
  }
  async handleStreamingResponse(response) {
    const reader = response.body?.getReader();
    if (!reader) return;
    const decoder = new TextDecoder();
    const last = this.messages[this.messages.length - 1];
    if (!last) return;
    let sseBuffer = "";
    try {
      while (true) {
        const { done, value } = await reader.read();
        const text = decoder.decode(value || new Uint8Array(), { stream: !done });
        sseBuffer += text;
        const lines = sseBuffer.split("\n");
        sseBuffer = lines.pop() || "";
        for (const line of lines) {
          const trimmedLine = line.trim();
          if (!trimmedLine) continue;
          const payload = trimmedLine.startsWith("data: ") ? trimmedLine.slice(6).trim() : trimmedLine;
          if (!payload.startsWith("{") && payload !== "[DONE]") {
            continue;
          }
          if (!payload || payload === "[DONE]") {
            continue;
          }
          try {
            const event = JSON.parse(payload);
            if (event.type === "chunk" && event.text) {
              last.text += event.text;
              this.updateLastBubbleText(last.text, true);
            } else if (event.type === "session" && event.sessionId) {
              this.setSessionId(event.sessionId);
            } else if (event.type === "done") {
              continue;
            }
            if (event.type === "text-delta" && event.delta) {
              last.text += event.delta;
              this.updateLastBubbleText(last.text, true);
            } else if (event.type === "start" && event.messageMetadata?.sessionId) {
              this.setSessionId(event.messageMetadata.sessionId);
            } else if (event.type === "finish" && event.messageMetadata?.sessionId) {
              this.setSessionId(event.messageMetadata.sessionId);
            }
          } catch {
          }
        }
        if (done) {
          break;
        }
      }
    } finally {
      reader.releaseLock();
      this.persistMessages();
    }
  }
  async animateAssistantText(fullText) {
    const last = this.messages[this.messages.length - 1];
    if (!last) return;
    let out = "";
    for (const ch of fullText) {
      out += ch;
      last.text = out;
      this.updateLastBubbleText(out, true);
      await new Promise((resolve) => setTimeout(resolve, 12));
    }
    this.persistMessages();
  }
};
function init(config) {
  if (!config.workspaceId || !config.agentId) {
    throw new Error("workspaceId and agentId are required. You can get both from your KriyaOS workspace.");
  }
  const widget = new ChatWidgetRuntime(config);
  widget.init();
}
var ChatWidget = { init };
var index_default = ChatWidget;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ChatWidget,
  init
});
