/**
 * wpp-auth.js - WhatsApp Identity Provider
 * Generates a cryptographically secure, unchangeable ID based on WhatsApp Phone Number
 */

(function () {
    const SALT = "k9$HmP2@vL7*nQ4!8zXw1#cG5%yR3^tB";

    async function hashPhone(phone) {
        const encoder = new TextEncoder();
        const data = encoder.encode(phone + SALT);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('').toUpperCase();
        return "WA-" + hashHex.substring(0, 16);
    }

    async function waitForWPP() {
        return new Promise((resolve) => {
            const check = () => {
                if (window.WPP && window.WPP.whatsapp && window.WPP.whatsapp.UserPrefs) {
                    resolve(window.WPP);
                } else {
                    setTimeout(check, 100);
                }
            };
            check();
        });
    }

    async function initAuth(attempt = 1) {
        try {
            console.log(`🛡️ Initializing PrimeSender Hashed Auth (Attempt ${attempt})...`);
            await waitForWPP();

            // Extract phone number from WPP UserPrefs
            const me = window.WPP.whatsapp.UserPrefs.getMaybeMeUser();
            if (!me || !me.user) {
                console.warn("⚠️ Phone number not found yet. Retrying...");
                setTimeout(() => initAuth(attempt), 2000);
                return;
            }

            const phone = me.user;
            const hashedID = await hashPhone(phone);
            
            // Get user display name if available (PHASE 15.3: Enhanced Extraction)
            const contact = window.WPP.whatsapp.ContactStore.get(me);
            let myName = contact?.__x_name || contact?.__x_pushname || contact?.__x_verifiedName || contact?.__x_formattedName;

            if (hashedID) localStorage.setItem('ps_device_id', hashedID);
            if (phone) localStorage.setItem('ps_wa_phone', phone);

            const isRealName = myName && myName.trim() !== "" && myName !== "WhatsApp User";
            if (isRealName) {
                localStorage.setItem('ps_wa_name', myName);
            }

            if (!isRealName) {
                console.warn(`⚠️ Profile name not fully populated yet. Retrying in 5s (Attempt ${attempt})...`);
                setTimeout(() => initAuth(attempt + 1), 5000);
                
                // On the first attempt, post 'WhatsApp User' so the UI still loads without waiting indefinitely
                if (attempt === 1) {
                    window.postMessage({
                        type: "WA_AUTH_DATA",
                        hashedID: hashedID,
                        phone: phone,
                        name: "WhatsApp User"
                    }, "*");
                }
                return;
            }

            console.log("🆔 Generated ID:", hashedID, "| Name:", myName);

            window.postMessage({
                type: "WA_AUTH_DATA",
                hashedID: hashedID,
                phone: phone,
                name: myName
            }, "*");

        } catch (err) {
            console.error("❌ Auth Initialization Failed:", err);
        }
    }

    // Run when ready
    if (document.readyState === 'complete') {
        initAuth(1);
    } else {
        window.addEventListener('load', () => initAuth(1));
    }
})();
