/**
 * @license MIT
 * author: Cube Dev Team
 * @cube-dev/ui-kit v0.0.0-canary-c2a807a
 * Released under the MIT license.
 */

/**
 * ConditionNode Types and Helpers
 *
 * Core data structures for representing style conditions as an abstract syntax tree.
 * Used throughout the pipeline for parsing, simplification, and CSS generation.
 */
// ============================================================================
// Constructor Functions
// ============================================================================
/**
 * Create a TRUE condition (matches everything)
 */
export function trueCondition() {
    return { kind: 'true' };
}
/**
 * Create a FALSE condition (matches nothing)
 */
export function falseCondition() {
    return { kind: 'false' };
}
/**
 * Create an AND compound condition
 */
export function and(...children) {
    const filtered = [];
    for (const child of children) {
        // Short-circuit on FALSE
        if (child.kind === 'false') {
            return falseCondition();
        }
        // Skip TRUE (identity for AND)
        if (child.kind === 'true') {
            continue;
        }
        // Flatten nested ANDs
        if (child.kind === 'compound' && child.operator === 'AND') {
            filtered.push(...child.children);
        }
        else {
            filtered.push(child);
        }
    }
    if (filtered.length === 0) {
        return trueCondition();
    }
    if (filtered.length === 1) {
        return filtered[0];
    }
    return {
        kind: 'compound',
        operator: 'AND',
        children: filtered,
    };
}
/**
 * Create an OR compound condition
 */
export function or(...children) {
    const filtered = [];
    for (const child of children) {
        // Short-circuit on TRUE
        if (child.kind === 'true') {
            return trueCondition();
        }
        // Skip FALSE (identity for OR)
        if (child.kind === 'false') {
            continue;
        }
        // Flatten nested ORs
        if (child.kind === 'compound' && child.operator === 'OR') {
            filtered.push(...child.children);
        }
        else {
            filtered.push(child);
        }
    }
    if (filtered.length === 0) {
        return falseCondition();
    }
    if (filtered.length === 1) {
        return filtered[0];
    }
    return {
        kind: 'compound',
        operator: 'OR',
        children: filtered,
    };
}
/**
 * Negate a condition
 */
export function not(node) {
    // NOT(TRUE) = FALSE
    if (node.kind === 'true') {
        return falseCondition();
    }
    // NOT(FALSE) = TRUE
    if (node.kind === 'false') {
        return trueCondition();
    }
    // NOT(state) = toggle negated flag
    if (node.kind === 'state') {
        return {
            ...node,
            negated: !node.negated,
            uniqueId: node.negated
                ? node.uniqueId.replace(/^!/, '')
                : `!${node.uniqueId}`,
        };
    }
    // NOT(AND(a, b, ...)) = OR(NOT(a), NOT(b), ...) - De Morgan's law
    if (node.kind === 'compound' && node.operator === 'AND') {
        return or(...node.children.map((c) => not(c)));
    }
    // NOT(OR(a, b, ...)) = AND(NOT(a), NOT(b), ...) - De Morgan's law
    if (node.kind === 'compound' && node.operator === 'OR') {
        return and(...node.children.map((c) => not(c)));
    }
    // Fallback - should not reach here
    return node;
}
// ============================================================================
// Condition Type Checking
// ============================================================================
/**
 * Check if a condition is a compound condition
 */
export function isCompoundCondition(node) {
    return node.kind === 'compound';
}
// ============================================================================
// UniqueId Generation
// ============================================================================
/**
 * Generate a normalized unique ID for a modifier condition
 */
export function modifierUniqueId(attribute, value, operator = '=', negated = false) {
    const base = value
        ? `mod:${attribute}${operator}${value}`
        : `mod:${attribute}`;
    return negated ? `!${base}` : base;
}
/**
 * Generate a normalized unique ID for a pseudo condition
 */
export function pseudoUniqueId(pseudo, negated = false) {
    const base = `pseudo:${pseudo}`;
    return negated ? `!${base}` : base;
}
/**
 * Generate a normalized unique ID for a media condition
 */
export function mediaUniqueId(subtype, props, negated = false) {
    let base;
    if (subtype === 'dimension') {
        const parts = ['media', 'dim', props.dimension];
        if (props.lowerBound) {
            parts.push(props.lowerBound.inclusive ? '>=' : '>');
            parts.push(props.lowerBound.value);
        }
        if (props.upperBound) {
            parts.push(props.upperBound.inclusive ? '<=' : '<');
            parts.push(props.upperBound.value);
        }
        base = parts.join(':');
    }
    else if (subtype === 'feature') {
        base = props.featureValue
            ? `media:feat:${props.feature}:${props.featureValue}`
            : `media:feat:${props.feature}`;
    }
    else {
        base = `media:type:${props.mediaType}`;
    }
    return negated ? `!${base}` : base;
}
/**
 * Generate a normalized unique ID for a container condition
 */
export function containerUniqueId(subtype, props, negated = false) {
    let base;
    const name = props.containerName || '_';
    if (subtype === 'dimension') {
        const parts = ['container', 'dim', name, props.dimension];
        if (props.lowerBound) {
            parts.push(props.lowerBound.inclusive ? '>=' : '>');
            parts.push(props.lowerBound.value);
        }
        if (props.upperBound) {
            parts.push(props.upperBound.inclusive ? '<=' : '<');
            parts.push(props.upperBound.value);
        }
        base = parts.join(':');
    }
    else {
        base = props.propertyValue
            ? `container:style:${name}:--${props.property}:${props.propertyValue}`
            : `container:style:${name}:--${props.property}`;
    }
    return negated ? `!${base}` : base;
}
/**
 * Generate a normalized unique ID for a root condition
 */
export function rootUniqueId(selector, negated = false) {
    const base = `root:${selector}`;
    return negated ? `!${base}` : base;
}
/**
 * Generate a normalized unique ID for an own condition
 */
export function ownUniqueId(innerUniqueId, negated = false) {
    const base = `own:${innerUniqueId}`;
    return negated ? `!${base}` : base;
}
/**
 * Generate a normalized unique ID for a starting condition
 */
export function startingUniqueId(negated = false) {
    return negated ? '!starting' : 'starting';
}
/**
 * Generate a normalized unique ID for a supports condition
 */
export function supportsUniqueId(subtype, condition, negated = false) {
    const base = `supports:${subtype}:${condition}`;
    return negated ? `!${base}` : base;
}
// ============================================================================
// Condition Creation Helpers
// ============================================================================
/**
 * Create a modifier condition
 */
export function createModifierCondition(attribute, value, operator = '=', negated = false, raw) {
    return {
        kind: 'state',
        type: 'modifier',
        negated,
        raw: raw || (value ? `${attribute}${operator}${value}` : attribute),
        uniqueId: modifierUniqueId(attribute, value, operator, negated),
        attribute,
        value,
        operator: value ? operator : undefined,
    };
}
/**
 * Create a pseudo condition
 */
export function createPseudoCondition(pseudo, negated = false, raw) {
    return {
        kind: 'state',
        type: 'pseudo',
        negated,
        raw: raw || pseudo,
        uniqueId: pseudoUniqueId(pseudo, negated),
        pseudo,
    };
}
/**
 * Create a media dimension condition
 */
export function createMediaDimensionCondition(dimension, lowerBound, upperBound, negated = false, raw) {
    return {
        kind: 'state',
        type: 'media',
        subtype: 'dimension',
        negated,
        raw: raw || `@media(${dimension})`,
        uniqueId: mediaUniqueId('dimension', { dimension, lowerBound, upperBound }, negated),
        dimension,
        lowerBound,
        upperBound,
    };
}
/**
 * Create a media feature condition
 */
export function createMediaFeatureCondition(feature, featureValue, negated = false, raw) {
    return {
        kind: 'state',
        type: 'media',
        subtype: 'feature',
        negated,
        raw: raw || `@media(${feature}${featureValue ? `: ${featureValue}` : ''})`,
        uniqueId: mediaUniqueId('feature', { feature, featureValue }, negated),
        feature,
        featureValue,
    };
}
/**
 * Create a media type condition
 */
export function createMediaTypeCondition(mediaType, negated = false, raw) {
    return {
        kind: 'state',
        type: 'media',
        subtype: 'type',
        negated,
        raw: raw || `@media:${mediaType}`,
        uniqueId: mediaUniqueId('type', { mediaType }, negated),
        mediaType,
    };
}
/**
 * Create a container dimension condition
 */
export function createContainerDimensionCondition(dimension, lowerBound, upperBound, containerName, negated = false, raw) {
    return {
        kind: 'state',
        type: 'container',
        subtype: 'dimension',
        negated,
        raw: raw || `@(${containerName ? containerName + ', ' : ''}${dimension})`,
        uniqueId: containerUniqueId('dimension', { containerName, dimension, lowerBound, upperBound }, negated),
        containerName,
        dimension,
        lowerBound,
        upperBound,
    };
}
/**
 * Create a container style condition
 */
export function createContainerStyleCondition(property, propertyValue, containerName, negated = false, raw) {
    return {
        kind: 'state',
        type: 'container',
        subtype: 'style',
        negated,
        raw: raw ||
            `@(${containerName ? containerName + ', ' : ''}$${property}${propertyValue ? '=' + propertyValue : ''})`,
        uniqueId: containerUniqueId('style', { containerName, property, propertyValue }, negated),
        containerName,
        property,
        propertyValue,
    };
}
/**
 * Create a root condition
 */
export function createRootCondition(selector, negated = false, raw) {
    return {
        kind: 'state',
        type: 'root',
        negated,
        raw: raw || `@root(${selector})`,
        uniqueId: rootUniqueId(selector, negated),
        selector,
    };
}
/**
 * Create an own condition
 */
export function createOwnCondition(innerCondition, negated = false, raw) {
    const innerUniqueId = getConditionUniqueId(innerCondition);
    return {
        kind: 'state',
        type: 'own',
        negated,
        raw: raw || `@own(...)`,
        uniqueId: ownUniqueId(innerUniqueId, negated),
        innerCondition,
    };
}
/**
 * Create a starting condition
 */
export function createStartingCondition(negated = false, raw) {
    return {
        kind: 'state',
        type: 'starting',
        negated,
        raw: raw || '@starting',
        uniqueId: startingUniqueId(negated),
    };
}
/**
 * Create a supports condition
 *
 * @param subtype 'feature' for @supports(display: grid), 'selector' for @supports($, :has(*))
 * @param condition The condition string (e.g., "display: grid" or ":has(*)")
 */
export function createSupportsCondition(subtype, condition, negated = false, raw) {
    return {
        kind: 'state',
        type: 'supports',
        subtype,
        negated,
        raw: raw || `@supports(${condition})`,
        uniqueId: supportsUniqueId(subtype, condition, negated),
        condition,
    };
}
// ============================================================================
// Utility Functions
// ============================================================================
/**
 * Get the unique ID for any condition node
 */
export function getConditionUniqueId(node) {
    if (node.kind === 'true') {
        return 'TRUE';
    }
    if (node.kind === 'false') {
        return 'FALSE';
    }
    if (node.kind === 'state') {
        return node.uniqueId;
    }
    if (node.kind === 'compound') {
        const childIds = node.children.map(getConditionUniqueId).sort();
        return `${node.operator}(${childIds.join(',')})`;
    }
    return 'UNKNOWN';
}

        