function coreUnwrapLogic(library, exportName, debug = false) {
    if (library == null) {
        throw new Error(`Cannot unwrap export '${exportName}' from null or undefined library`);
    }
    const libraryType = typeof library;
    if (libraryType === 'string' || libraryType === 'number' || libraryType === 'boolean' || libraryType === 'symbol' || libraryType === 'bigint') {
        throw new Error(`Cannot unwrap export '${exportName}' from ${libraryType} value. Library must be an object or function.`);
    }
    if (libraryType === 'function') {
        if (debug) {
            console.log(`📦 Library is a single function/class, returning it for '${exportName}'`);
            console.log(`   Function name: ${library.name || 'anonymous'}`);
            const hasStatics = Object.keys(library).some(key => key !== 'prototype' && key !== 'length' && key !== 'name' && key !== 'caller' && key !== 'arguments');
            if (hasStatics) {
                console.log(`   Has static properties: ${Object.keys(library).filter(k => k !== 'prototype' && k !== 'length' && k !== 'name' && k !== 'caller' && k !== 'arguments').join(', ')}`);
            }
        }
        return library;
    }
    if (libraryType === 'object') {
        const objectKeys = Object.keys(library).filter(key => key !== '__esModule' && key !== 'default');
        if (objectKeys.length === 1 && typeof library[objectKeys[0]] === 'function') {
            if (debug) {
                console.log(`📦 Library has single exported function '${objectKeys[0]}', using it for '${exportName}'`);
            }
            return library[objectKeys[0]];
        }
        if (objectKeys.length === 0 && library.default && typeof library.default === 'function') {
            if (debug) {
                console.log(`📦 Library only has default export (function), using it for '${exportName}'`);
            }
            return library.default;
        }
    }
    if (debug) {
        console.log(`📦 Library is a complex object, attempting standard unwrapping for '${exportName}'`);
    }
    if (exportName.includes('.')) {
        const parts = exportName.split('.');
        let current = library;
        let pathTaken = 'library';
        for (let i = 0; i < parts.length; i++) {
            const part = parts[i];
            if (!current) {
                if (debug) {
                    console.log(`   ❌ Cannot access '${part}' - parent is null/undefined at path: ${pathTaken}`);
                }
                return undefined;
            }
            if (i === 0) {
                if (debug) {
                    console.log(`   Checking library.${part}...`);
                }
                const firstComponent = current[part];
                if (debug) {
                    console.log(`   Checking library.default.${part}...`);
                }
                const firstDefault = current.default?.[part];
                if (firstComponent) {
                    current = firstComponent;
                    pathTaken = `library.${part}`;
                    if (debug) {
                        console.log(`   ✅ Found via ${pathTaken}`);
                    }
                }
                else if (firstDefault) {
                    current = firstDefault;
                    pathTaken = `library.default.${part}`;
                    if (debug) {
                        console.log(`   ✅ Found via ${pathTaken}`);
                    }
                }
                else {
                    if (debug) {
                        console.log(`   ❌ Could not find '${part}' in library`);
                    }
                    return undefined;
                }
            }
            else {
                if (debug) {
                    console.log(`   Checking ${pathTaken}.${part}...`);
                }
                if (current[part]) {
                    current = current[part];
                    pathTaken += `.${part}`;
                    if (debug) {
                        console.log(`   ✅ Found via ${pathTaken}`);
                    }
                }
                else if (current.default?.[part]) {
                    current = current.default[part];
                    pathTaken += `.default.${part}`;
                    if (debug) {
                        console.log(`   ✅ Found via ${pathTaken}.default`);
                    }
                }
                else {
                    if (debug) {
                        console.log(`   ❌ Could not find '${part}' at path: ${pathTaken}`);
                    }
                    return undefined;
                }
            }
        }
        const isValidExport = (obj) => {
            return obj != null;
        };
        if (isValidExport(current)) {
            if (debug) {
                console.log(`✅ Successfully unwrapped '${exportName}' via: ${pathTaken}`);
                const exportType = typeof current === 'function' ?
                    (current.prototype?.isReactComponent ? 'React class component' : 'function/component') :
                    (typeof current === 'object' ? 'object/utility' : typeof current);
                console.log(`   Export type: ${exportType}`);
            }
            return current;
        }
        else if (current?.default && isValidExport(current.default)) {
            if (debug) {
                console.log(`✅ Successfully unwrapped '${exportName}' via: ${pathTaken}.default`);
            }
            return current.default;
        }
        else {
            if (debug) {
                console.log(`   ❌ '${exportName}' at ${pathTaken} is null/undefined`);
            }
            return undefined;
        }
    }
    let unwrapPath = '';
    let component;
    const isValidExport = (obj) => {
        return obj != null;
    };
    if (debug) {
        console.log(`   Checking library.${exportName}...`);
    }
    const directComponent = library[exportName];
    if (debug && directComponent) {
        console.log(`   Checking library.${exportName}.default...`);
    }
    const moduleDefault = directComponent?.default;
    if (debug && library.default) {
        console.log(`   Checking library.default.${exportName}...`);
    }
    const libraryDefault = library.default?.[exportName];
    if (debug && libraryDefault) {
        console.log(`   Checking library.default.${exportName}.default...`);
    }
    const libraryDefaultModule = library.default?.[exportName]?.default;
    if (isValidExport(directComponent)) {
        component = directComponent;
        unwrapPath = `library.${exportName}`;
        if (debug) {
            console.log(`   ✅ Found via ${unwrapPath}`);
            const exportType = typeof directComponent === 'function' ? 'function' :
                typeof directComponent === 'object' ? 'object' : typeof directComponent;
            console.log(`   Export type: ${exportType}`);
        }
    }
    else if (isValidExport(moduleDefault)) {
        component = moduleDefault;
        unwrapPath = `library.${exportName}.default`;
        if (debug) {
            console.log(`   ✅ Found via ${unwrapPath}`);
        }
    }
    else if (isValidExport(libraryDefault)) {
        component = libraryDefault;
        unwrapPath = `library.default.${exportName}`;
        if (debug) {
            console.log(`   ✅ Found via ${unwrapPath}`);
        }
    }
    else if (isValidExport(libraryDefaultModule)) {
        component = libraryDefaultModule;
        unwrapPath = `library.default.${exportName}.default`;
        if (debug) {
            console.log(`   ✅ Found via ${unwrapPath}`);
        }
    }
    if (debug && !component) {
        console.log(`   ❌ Could not unwrap '${exportName}' from library (all paths were null/undefined)`);
        console.log('   Library structure:');
        console.log('   - Top-level keys:', Object.keys(library).slice(0, 10).join(', '), Object.keys(library).length > 10 ? '...' : '');
        console.log(`   - library.${exportName}:`, directComponent);
        if (library.default) {
            console.log('   - library.default exists, keys:', Object.keys(library.default).slice(0, 10).join(', '));
        }
    }
    return component;
}
export function unwrapLibraryComponent(library, exportName, debug = false) {
    try {
        return coreUnwrapLogic(library, exportName, debug);
    }
    catch (error) {
        if (debug) {
            console.error(`🚫 Error unwrapping export '${exportName}':`, error.message);
        }
        throw error;
    }
}
export function unwrapLibraryComponents(library, ...exportNames) {
    let debug = false;
    let names = exportNames;
    const lastArg = exportNames[exportNames.length - 1];
    if (typeof lastArg === 'boolean') {
        debug = lastArg;
        names = exportNames.slice(0, -1);
    }
    const components = {};
    const found = [];
    const notFound = [];
    const libraryType = typeof library;
    if (library == null ||
        libraryType === 'string' ||
        libraryType === 'number' ||
        libraryType === 'boolean' ||
        libraryType === 'symbol' ||
        libraryType === 'bigint') {
        try {
            coreUnwrapLogic(library, names[0] || 'unknown', debug);
        }
        catch (error) {
            if (debug) {
                console.error(`🚫 ${error.message}`);
            }
            throw error;
        }
    }
    if (libraryType === 'function') {
        if (debug) {
            console.log(`📦 Library is a single function/class, returning it for all ${names.length} requested names`);
        }
        for (const name of names) {
            components[name] = library;
            found.push(name);
        }
    }
    else {
        for (const name of names) {
            try {
                const component = coreUnwrapLogic(library, name, false);
                if (component) {
                    components[name] = component;
                    if (name.includes('.')) {
                        const lastPart = name.split('.').pop();
                        if (lastPart && !components[lastPart]) {
                            components[lastPart] = component;
                        }
                    }
                    found.push(name);
                }
                else {
                    notFound.push(name);
                }
            }
            catch (error) {
                throw error;
            }
        }
    }
    if (debug) {
        if (found.length > 0) {
            console.log(`📦 Successfully unwrapped ${found.length} components:`, found.join(', '));
        }
        if (notFound.length > 0) {
            console.warn(`⚠️ Could not unwrap ${notFound.length} components:`, notFound.join(', '));
        }
    }
    return components;
}
export function unwrapAllLibraryComponents(library, debug = false) {
    const components = {};
    const libraryType = typeof library;
    if (library == null ||
        libraryType === 'string' ||
        libraryType === 'number' ||
        libraryType === 'boolean' ||
        libraryType === 'symbol' ||
        libraryType === 'bigint') {
        try {
            coreUnwrapLogic(library, 'auto-detect', debug);
        }
        catch (error) {
            if (debug) {
                console.error(`🚫 ${error.message}`);
            }
            throw error;
        }
    }
    if (libraryType === 'function') {
        const functionName = library.name || 'Component';
        if (debug) {
            console.log(`📦 Library is a single function/class '${functionName}', returning it as the only component`);
        }
        components[functionName] = library;
        return components;
    }
    const looksLikeComponentName = (key) => {
        if (!key || key.length === 0)
            return false;
        if (key[0] !== key[0].toUpperCase())
            return false;
        if (['__esModule', 'VERSION', 'version', 'default'].includes(key))
            return false;
        return /[a-z]/.test(key);
    };
    const checkedKeys = new Set();
    for (const key of Object.keys(library)) {
        if (looksLikeComponentName(key)) {
            try {
                const component = coreUnwrapLogic(library, key, false);
                if (component) {
                    components[key] = component;
                    checkedKeys.add(key);
                }
            }
            catch (error) {
            }
        }
    }
    if (library.default && typeof library.default === 'object') {
        for (const key of Object.keys(library.default)) {
            if (!checkedKeys.has(key) && looksLikeComponentName(key)) {
                try {
                    const component = coreUnwrapLogic(library, key, false);
                    if (component) {
                        components[key] = component;
                        checkedKeys.add(key);
                    }
                }
                catch (error) {
                }
            }
        }
    }
    if (debug) {
        const exportNames = Object.keys(components);
        if (exportNames.length > 0) {
            console.log(`🔍 Auto-detected ${exportNames.length} components from library`);
            console.log('   Components:', exportNames.slice(0, 20).join(', '), exportNames.length > 20 ? `... and ${exportNames.length - 20} more` : '');
        }
        else {
            console.warn('⚠️ No components auto-detected from library');
            console.log('   Library type:', typeof library);
            if (library) {
                console.log('   Top-level keys:', Object.keys(library).slice(0, 10).join(', '));
            }
        }
    }
    return components;
}
export const unwrapComponent = unwrapLibraryComponent;
export const unwrapComponents = (library, exportNames, debug = false) => {
    return unwrapLibraryComponents(library, ...exportNames, debug);
};
export const unwrapAllComponents = unwrapAllLibraryComponents;
//# sourceMappingURL=component-unwrapper.js.map