// --- START OF FILE facebook-capi.js ---

// ==========================================
// FACEBOOK CONVERSION API (CAPI) MODULE
// Features: Server-Side Tracking, Audience Segmentation, Data Hashing
// Updated: Supports 'Visitor_Segment' for Wealth Targeting
// ==========================================

export default class FacebookCAPI {
    /**
     * @param {string} accessToken - User's FB System User Access Token
     * @param {string} pixelId - User's FB Pixel ID
     */
    constructor(accessToken, pixelId) {
        this.accessToken = accessToken;
        this.pixelId = pixelId;
        this.apiUrl = `https://graph.facebook.com/v19.0/${pixelId}/events`;
    }

    /**
     * Helper: Hash data using SHA-256 (Required by Facebook)
     */
    async hashData(input) {
        if (!input) return null;
        const normalized = input.trim().toLowerCase();
        const msgBuffer = new TextEncoder().encode(normalized);
        const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    }

    /**
     * Helper: Get Cookie Value (For _fbp, _fbc matching)
     */
    getCookie(name) {
        const value = `; ${document.cookie}`;
        const parts = value.split(`; ${name}=`);
        if (parts.length === 2) return parts.pop().split(';').shift();
        return null;
    }

    /**
     * 🚀 NEW: Send Custom Events (For Audience Segmentation)
     * Used to send Wealth Class events like 'Elite', 'Aspiring', 'Standard'
     * @param {string} eventName - e.g., "Elite"
     * @param {Object} customData - e.g., { wealth_score: 90, gpu_model: 'Apple M1' }
     * @param {Object} userData - Optional PII (email, phone, ip)
     */
    async sendCustomEvent(eventName, customData = {}, userData = {}) {
        if (!this.accessToken || !this.pixelId) return;

        try {
            // 1. Prepare User Data (Server-Side Matching)
            const user_data_payload = {
                client_ip_address: userData.ip || null,
                client_user_agent: userData.userAgent || navigator.userAgent,
                fbp: this.getCookie('_fbp'),
                fbc: this.getCookie('_fbc')
            };

            // Hash PII if provided
            if (userData.phone) user_data_payload.ph = [await this.hashData(userData.phone)];
            if (userData.email) user_data_payload.em = [await this.hashData(userData.email)];

            // 2. Construct Payload
            const payload = {
                data: [
                    {
                        event_name: eventName,
                        event_time: Math.floor(Date.now() / 1000),
                        event_source_url: window.location.href,
                        action_source: "website",
                        user_data: user_data_payload,
                        custom_data: customData // e.g., { wealth_score: 90, gpu_model: 'Apple M1' }
                    }
                ],
                access_token: this.accessToken
            };

            // 3. Send to Facebook
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            const result = await response.json();
            
            if (response.ok) {
                console.log(`FB CAPI (${eventName}) Sent:`, customData);
                return { success: true, eventId: result.fbtrace_id };
            } else {
                console.warn(`FB CAPI (${eventName}) Failed:`, result);
                return { success: false, error: result.error?.message };
            }

        } catch (error) {
            console.error("FB CAPI Exception:", error);
            return { success: false, error: error.message };
        }
    }

    /**
     * Send Verified Purchase Event (Standard)
     */
    async sendVerifiedPurchase(order, orderId) {
        if (!this.accessToken || !this.pixelId) return { success: false, message: "Credentials missing" };

        try {
            // 1. Prepare User Data
            const customerPhone = order.customerInfo?.phone || '';
            const customerName = order.customerInfo?.name || '';
            
            const nameParts = customerName.split(' ');
            const firstName = nameParts[0] || '';
            const lastName = nameParts.length > 1 ? nameParts.slice(1).join(' ') : '';

            const hashedPhone = await this.hashData(customerPhone);
            const hashedFn = await this.hashData(firstName);
            const hashedLn = await this.hashData(lastName);
            const hashedCity = await this.hashData(order.customerInfo?.address || '');

            // 2. Prepare Content Data
            const items = order.items ? (Array.isArray(order.items) ? order.items : Object.values(order.items)) : [];
            const contents = items.map(item => ({
                id: item.id || 'unknown_sku',
                quantity: parseInt(item.quantity || 1),
                item_price: parseFloat(item.price || 0)
            }));

            const meta = order.meta || {};
            const user_data = {};
            if (hashedPhone) user_data.ph = [hashedPhone];
            if (hashedFn) user_data.fn = [hashedFn];
            if (hashedLn) user_data.ln = [hashedLn];
            if (hashedCity) user_data.ct = [hashedCity];
            if (meta.ip && meta.ip !== 'Unknown') user_data.client_ip_address = meta.ip;
            const ua = meta.userAgent || navigator.userAgent;
            if (ua) user_data.client_user_agent = ua;
            const fbpVal = meta.fbp || this.getCookie('_fbp');
            const fbcVal = meta.fbc || this.getCookie('_fbc');
            if (fbpVal) user_data.fbp = fbpVal;
            if (fbcVal) user_data.fbc = fbcVal;

            const eventObj = {
                event_name: "Purchase",
                event_time: Math.floor(Date.now() / 1000),
                event_source_url: meta.eventSourceUrl || window.location.href,
                action_source: "website",
                user_data,
                custom_data: {
                    currency: "BDT",
                    value: parseFloat(order.totalBill || 0),
                    order_id: orderId,
                    content_ids: items.map(i => i.id || 'sku'),
                    content_type: "product",
                    contents: contents,
                    num_items: items.length
                }
            };
            if (meta.fbPurchaseEventId) {
                eventObj.event_id = meta.fbPurchaseEventId;
            }

            // 3. Payload
            const payload = {
                data: [eventObj],
                access_token: this.accessToken
            };

            // 4. Send
            const response = await fetch(this.apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            const result = await response.json();

            if (response.ok) {
                console.log("FB CAPI Purchase Sent!", result);
                return { success: true, eventId: result.fbtrace_id };
            } else {
                console.error("FB CAPI Purchase Error:", result);
                return { success: false, error: result.error?.message };
            }

        } catch (error) {
            return { success: false, error: error.message };
        }
    }
}