function isRecord(value) {
    return typeof value === "object" && value !== null;
}
export function isBotState(value) {
    if (!isRecord(value)) {
        return false;
    }
    return (Array.isArray(value.messages) &&
        typeof value.isMinimized === "boolean" &&
        typeof value.isOpened === "boolean" &&
        typeof value.isExpanded === "boolean" &&
        typeof value.conversationId === "string" &&
        typeof value.projectId === "string" &&
        typeof value.newChat === "boolean");
}
const DEFAULT_MAX_BYTES = 3800;
const MAX_COOKIE_SIZE = 4000;
function getByteLength(value) {
    if (typeof TextEncoder !== "undefined") {
        return new TextEncoder().encode(value).length;
    }
    return value.length;
}
export function getCookie(name) {
    if (typeof document === "undefined") {
        return null;
    }
    const escapedName = name.replace(/([.*+?^${}()|[\]\\])/g, "\\$1");
    const match = document.cookie.match(new RegExp(`(?:^|; )${escapedName}=([^;]*)`));
    return match ? decodeURIComponent(match[1]) : null;
}
export function setCookie(name, value, options = {}) {
    var _a, _b, _c, _d;
    if (typeof document === "undefined") {
        return false;
    }
    const path = (_a = options.path) !== null && _a !== void 0 ? _a : "/";
    const sameSite = (_b = options.sameSite) !== null && _b !== void 0 ? _b : "Lax";
    const secure = (_c = options.secure) !== null && _c !== void 0 ? _c : (typeof window !== "undefined" && window.location.protocol === "https:");
    const domain = options.domain;
    let cookie = `${name}=${encodeURIComponent(value)}`;
    if (domain) {
        if (!/^[a-zA-Z0-9._-]+$/.test(domain)) {
            console.warn("AI12Z: Invalid cookie domain characters");
            return false;
        }
        cookie += `; Domain=${domain}`;
    }
    cookie += `; Path=${path}`;
    cookie += `; SameSite=${sameSite}`;
    const maxAgeDays = (_d = options.maxAgeDays) !== null && _d !== void 0 ? _d : 7; // Default 7 days
    const maxAge = maxAgeDays * 24 * 60 * 60;
    cookie += `; Max-Age=${maxAge}`;
    if (secure) {
        cookie += `; Secure`;
    }
    // Check total cookie size after fully building the string
    const totalSize = getByteLength(cookie);
    if (totalSize > MAX_COOKIE_SIZE) {
        console.warn(`AI12Z: Cookie value exceeds safe limit (${totalSize} bytes). Cookie not set.`);
        return false;
    }
    document.cookie = cookie;
    return true;
}
export function removeCookie(name, path = "/", domain) {
    setCookie(name, "", { maxAgeDays: 0, path, domain });
}
export function getJsonCookie(name, validator) {
    const raw = getCookie(name);
    if (!raw) {
        return null;
    }
    try {
        const parsed = JSON.parse(raw);
        if (validator && !validator(parsed)) {
            console.warn(`AI12Z: Cookie '${name}' failed validation`);
            return null;
        }
        return parsed;
    }
    catch (error) {
        console.warn("AI12Z: Failed to parse cookie JSON:", error);
        return null;
    }
}
export function setJsonCookie(name, data, options = {}) {
    var _a, _b;
    const cookieData = Object.assign({}, data);
    if (((_a = cookieData.messages) === null || _a === void 0 ? void 0 : _a.length) > 0) {
        cookieData.messages = [];
    }
    const json = JSON.stringify(cookieData);
    const encoded = encodeURIComponent(json);
    const maxBytes = (_b = options.maxBytes) !== null && _b !== void 0 ? _b : DEFAULT_MAX_BYTES;
    if (getByteLength(encoded) > maxBytes) {
        console.warn(`AI12Z: Cookie '${name}' exceeds size limit and was skipped`);
        return false;
    }
    return setCookie(name, json, options);
}
export function getValidCookieDomain(subDomain) {
    if (!subDomain)
        return undefined;
    // SSR / prerender safe check
    if (typeof window === "undefined") {
        return undefined;
    }
    const bare = subDomain.replace(/^\./, "");
    const currentHost = window.location.hostname;
    if (currentHost === bare || currentHost.endsWith("." + bare)) {
        return subDomain;
    }
    console.warn("AI12Z: subDomain does not match current host");
    return undefined;
}
/**
 * Deletes a cookie by name
 * @param name - Cookie name to delete
 * @param options - Optional path and domain (must match original cookie)
 */
export function deleteJsonCookie(name, options = {}) {
    const { path = "/", domain } = options;
    if (typeof document === "undefined") {
        return;
    }
    removeCookie(name, path, domain);
}
