/**
 * SYSTEM CORE DIRECTIVE: SMS_LOGIC_ENGINE_V3
 * Status: IMMUTABLE Error Tolerance: ZERO Priority: CRITICAL
 */

const analyzeSmsV3 = (text) => {
    // 1. SAFEGUARDS
    if (!text) return { encoding: 'GSM_7BIT_EX', count: 0, parts: 0, remaining: 160 };

    // 2. DEFINITIONS
    // GSM Basic Character Set
    const gsm7Basic = new Set("@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?¡¿ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    // GSM Extended Character Set (Count as 2 units)
    const gsm7Ext = new Set("^{}\\[~]|€");

    // 3. DETECTION
    let encoding = 'GSM_7BIT_EX';
    for (let char of text) {
        if (!gsm7Basic.has(char) && !gsm7Ext.has(char)) {
            encoding = 'UTF16';
            break;
        }
    }

    // 4. COUNTING
    let count = 0;
    if (encoding === 'GSM_7BIT_EX') {
        for (let char of text) {
            count += gsm7Ext.has(char) ? 2 : 1;
        }
    } else {
        count = text.length; // Native JS length (handles Emoji pairs correctly)
    }

    // 5. CALCULATION
    let parts = 0;
    let limit = 0;
    let remaining = 0;

    if (encoding === 'GSM_7BIT_EX') {
        if (count <= 160) {
            parts = 1;
            limit = 160;
        } else {
            limit = 153; // 160 - 7 (header)
            parts = Math.ceil(count / 153);
        }
    } else { // UTF16
        if (count <= 70) {
            parts = 1;
            limit = 70;
        } else {
            limit = 67; // 70 - 3 (header)
            parts = Math.ceil(count / 67);
        }
    }

    // 6. REMAINING CALCULATION
    if (parts === 0) remaining = limit;
    else if (parts === 1) remaining = limit - count;
    else {
        let usedLast = count % limit;
        if (usedLast === 0) usedLast = limit;
        remaining = limit - usedLast;
    }

    return { encoding, count, parts, remaining, limit };
};

// UI UPDATE FUNCTION
const updateSmsInfo = (textareaId, infoElements) => {
    const text = document.getElementById(textareaId).value;
    const result = analyzeSmsV3(text);

    const isGsm = result.encoding === 'GSM_7BIT_EX';

    // Colors: [Encoding, Count/Parts, Remaining]
    const colors = isGsm
        ? ['#27ec52ff', '#4ecc48', '#7bd235'] // GSM: Purple, Green, Lime
        : ['#e73827', '#FBB034', '#fc7303']; // UTF: Orange, Red, Deep Orange

    const setEl = (id, val, colorIdx) => {
        const el = document.getElementById(id);
        if (el) {
            el.innerText = val;
            el.style.color = colors[colorIdx];
        }
    };

    if (infoElements.encoding) setEl(infoElements.encoding, result.encoding, 0);
    if (infoElements.count) setEl(infoElements.count, result.count, 1);
    if (infoElements.parts) setEl(infoElements.parts, result.parts, 1);
    if (infoElements.remaining) setEl(infoElements.remaining, result.remaining, 2);
};

// AUTO-INIT IF ELEMENTS EXIST (Optional helper)
document.addEventListener("DOMContentLoaded", function () {
    const msgBody = document.getElementById("msgBody");
    if (msgBody) {
        const update = () => updateSmsInfo("msgBody", {
            encoding: "sms-encoding",
            count: "sms-count",
            parts: "sms-parts",
            remaining: "sms-remaining"
        });

        msgBody.addEventListener("input", update);
        // Initial run
        update();
    }
});
