"use client";
'use strict';

var tslib_es6 = require('../../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.js');
var React = require('react');
var fingerprintClient = require('./fingerprint-client.js');
var fingerprintShared = require('./fingerprint-shared.js');

/**
 * Hook for managing fingerprint ID and anonymous user data
 * Accepts configuration to customize API endpoint and behavior
 */
function useFingerprint(config) {
    // 服务端渲染检查
    if (typeof window === 'undefined') {
        return {
            fingerprintId: null,
            xUser: null,
            xCredit: null,
            xSubscription: null,
            isLoading: false,
            isInitialized: false,
            error: 'Server-side rendering is not supported',
            initializeAnonymousUser: () => tslib_es6.__awaiter(this, void 0, void 0, function* () { }),
            refreshUserData: () => tslib_es6.__awaiter(this, void 0, void 0, function* () { }),
        };
    }
    const [fingerprintId, setFingerprintIdState] = React.useState(null);
    const [xUser, setXUser] = React.useState(null);
    const [xCredit, setXCredit] = React.useState(null);
    const [xSubscription, setXSubscription] = React.useState(null);
    const [isLoading, setIsLoading] = React.useState(true);
    const [isInitialized, setIsInitialized] = React.useState(false);
    const [error, setError] = React.useState(null);
    /**
     * 第一阶段：初始化fingerprint ID
     */
    const initializeFingerprintId = React.useCallback(() => tslib_es6.__awaiter(this, void 0, void 0, function* () {
        try {
            const currentFingerprintId = yield fingerprintClient.getOrGenerateFingerprintId();
            console.log('Initialized fingerprintId:', currentFingerprintId);
            setFingerprintIdState(currentFingerprintId);
            return currentFingerprintId;
        }
        catch (error) {
            console.error('Failed to initialize fingerprint ID:', error);
            setError('Failed to generate fingerprint ID');
            return null;
        }
    }), []);
    /**
     * 第二阶段：初始化匿名用户
     */
    const initializeAnonymousUser = React.useCallback(() => tslib_es6.__awaiter(this, void 0, void 0, function* () {
        var _a;
        if (!fingerprintId) {
            console.warn('Cannot initialize user: Fingerprint ID is missing', { fingerprintId, isLoading, isInitialized });
            setError('Cannot initialize user: Missing fingerprint ID');
            return;
        }
        try {
            setIsLoading(true);
            setError(null);
            console.log('Initializing anonymous user with fingerprintId:', fingerprintId);
            const fingerprintHeaders = yield fingerprintClient.createFingerprintHeaders();
            const response = yield fetch(config.apiEndpoint, {
                method: 'POST',
                headers: Object.assign({ 'Content-Type': 'application/json', [fingerprintShared.FINGERPRINT_SOURCE_REFER]: document.referrer || '' }, fingerprintHeaders),
                body: JSON.stringify({ fingerprintId }),
            });
            if (!response.ok) {
                const errorData = yield response.json().catch(() => ({}));
                throw new Error(errorData.error || 'Failed to initialize anonymous user');
            }
            const data = yield response.json();
            console.log('API response in initializeAnonymousUser:', data);
            if (data.success) {
                const updatedXUser = data.xUser || { userId: '', fingerprintId, clerkUserId: '', email: '', status: '', createdAt: '' };
                console.log('Setting xUser:', updatedXUser);
                setXUser(updatedXUser);
                setXCredit(data.xCredit || null);
                setXSubscription(data.xSubscription || null);
                setIsInitialized(true);
                if (((_a = data.xUser) === null || _a === void 0 ? void 0 : _a.fingerprintId) && data.xUser.fingerprintId !== fingerprintId) {
                    setFingerprintIdState(data.xUser.fingerprintId);
                }
            }
            else {
                throw new Error(data.error || 'Unknown error occurred');
            }
        }
        catch (err) {
            console.error('Failed to initialize anonymous user:', err);
            setError(err instanceof Error ? err.message : 'Unknown error');
        }
        finally {
            setIsLoading(false);
        }
    }), [fingerprintId, config.apiEndpoint]);
    /**
     * 刷新用户数据 - 使用POST请求（后端支持upsert逻辑）
     */
    const refreshUserData = React.useCallback(() => tslib_es6.__awaiter(this, void 0, void 0, function* () {
        if (!fingerprintId) {
            console.warn('Cannot refresh user data: Fingerprint ID is missing', { fingerprintId, isLoading, isInitialized });
            setError('Cannot refresh user data: Missing fingerprint ID');
            return;
        }
        try {
            setError(null);
            const fingerprintHeaders = yield fingerprintClient.createFingerprintHeaders();
            const response = yield fetch(config.apiEndpoint, {
                method: 'POST',
                headers: Object.assign({ 'Content-Type': 'application/json' }, fingerprintHeaders),
                body: JSON.stringify({ fingerprintId }),
            });
            if (!response.ok) {
                const errorData = yield response.json().catch(() => ({}));
                throw new Error(errorData.error || 'Failed to refresh user data');
            }
            const data = yield response.json();
            if (data.success) {
                const updatedXUser = data.xUser || { userId: '', fingerprintId, clerkUserId: '', email: '', status: '', createdAt: '' };
                setXUser(updatedXUser);
                setXCredit(data.xCredit || null);
                setXSubscription(data.xSubscription || null);
            }
        }
        catch (err) {
            console.error('Failed to refresh user data:', err);
            setError(err instanceof Error ? err.message : 'Unknown error');
        }
    }), [fingerprintId, config.apiEndpoint]);
    // 第一阶段：页面加载完成后生成指纹ID
    React.useEffect(() => {
        const initFingerprint = () => tslib_es6.__awaiter(this, void 0, void 0, function* () {
            setIsLoading(true);
            yield initializeFingerprintId();
            setIsLoading(false);
        });
        initFingerprint();
    }, [initializeFingerprintId]);
    // 第二阶段：有指纹ID后直接初始化用户（后端支持upsert逻辑）
    React.useEffect(() => {
        if (!fingerprintId || isInitialized || isLoading || error || config.autoInitialize === false)
            return;
        // 直接使用 POST 请求，后端会处理查询-不存在则创建的逻辑
        initializeAnonymousUser();
    }, [fingerprintId, isInitialized, isLoading, error, initializeAnonymousUser, config.autoInitialize]);
    return {
        fingerprintId,
        xUser,
        xCredit,
        xSubscription,
        isLoading,
        isInitialized,
        error,
        initializeAnonymousUser,
        refreshUserData,
    };
}

exports.useFingerprint = useFingerprint;
