
function showTab(tabId) {
    document.querySelectorAll('.iafwzcai-ai-settings-tab').forEach(tab => tab.classList.remove('active'));
    document.querySelectorAll('.iafwzcai-ai-settings-tab-content').forEach(content => content.classList.remove('active'));
    
    document.querySelector(`[onclick="showTab('${tabId}')"]`).classList.add('active');
    document.getElementById(tabId).classList.add('active');
}


const predefinedKeywords = {
    spam: "free, win, winner, congratulations, buy now, click here, urgent, limited time, special offer, cash, discount, deal, order now, money, prize, gift, 100% free, risk-free, guarantee, cheap, lottery, earn, income, investment, make money, fast cash, extra income, credit card, payday loan, work from home, best price, exclusive, act now, apply now, no obligation, trial, unlimited, bonus, incredible, miracle, debt, financial freedom, weight loss, prescription, casino, betting, loan, insurance, refund, bitcoin, forex, earn online, free trial, subscribe now, clearance, final sale, lowest price, hot deal, luxury, urgent action, verify, offer ends, act fast, online pharmacy, sex, porn, adult, viagrа, cialis, replica, fake, buy direct, instant, amazing deal, cash bonus, easy money, enlarge, extra cash, gambling, get paid, lose weight, miracle cure, online biz, profit, free gift, free money, quick cash, money back, limited supply, apply today, double your income, trial offer, while supplies last".split(", "),
    email: "test, demo, example, 123, abc, temp, user, fake, noreply, donotreply, spam, random, guest, anonymous, unknown, sample, mailtest, throwaway, placeholder, invalid, noreal, bogus, dummy, trial, testing, emailtest, autofill, noemail, invalidemail, mailme, emailme, yourmail, nomail, noname, testaccount, fakeuser, someemail, tempuser, tempaccount, trash, unverified, autofill123, test123, abc123, xyz, qwerty, lmnop, asdf, unknownuser, none, noone, nothing, null, void, tmp, disposable, quickmail, randommail, xyzmail".split(", "),
    publicEmails: "gmail.com, yahoo.com, outlook.com, hotmail.com, aol.com, icloud.com, mail.com, yandex.com, protonmail.com, zoho.com, gmx.com, fastmail.com, inbox.com, rediffmail.com, lycos.com, rocketmail.com, hushmail.com, mail.ru, rambler.ru, t-online.de, web.de, btinternet.com, orange.fr, live.com, msn.com, me.com, mac.com, qq.com, 126.com, 163.com, sina.com, yeah.net, naver.com, daum.net, hanmail.net, excite.com, comcast.net, bellsouth.net, cox.net, sbcglobal.net, charter.net, shaw.ca, rogers.com, telus.net, bigpond.com, optonline.net, att.net, frontier.com, verizon.net, earthlink.net".split(", ")
};

let tagData = {};

function addTag(containerId, tagText) {
    if (!tagData[containerId].includes(tagText)) {
        tagData[containerId].push(tagText);
        renderTags(containerId);
    }
}

function removeTag(containerId, tagText) {
    tagData[containerId] = tagData[containerId].filter(tag => tag !== tagText);
    renderTags(containerId);
}

function renderTags(containerId) {
    const tagContainer = document.getElementById(containerId);
    const tagInput = tagContainer.querySelector(".iafwzcai-ai-settings-input");

    tagContainer.innerHTML = "";

    tagData[containerId].forEach(tag => {
        const tagElement = document.createElement("span");
        tagElement.classList.add("iafwzcai-ai-settings-tag");
        tagElement.innerHTML = `${tag} <span class="iafwzcai-ai-settings-close" data-tag="${tag}">&times;</span>`;
        tagContainer.appendChild(tagElement);
    });

    tagContainer.appendChild(tagInput);
    tagInput.focus();
}

function setupTagInput(containerId, inputId, keywordType) {
    const tagContainer = document.getElementById(containerId);
    const tagInput = document.getElementById(inputId);

    if (!tagContainer || !tagInput) {
        return;
    }
   
    let keywords = getTagsById(containerId);
    
    if (!keywords || keywords.trim() === "") {
        tagData[containerId] = predefinedKeywords[keywordType] || [];
    } else {
        tagData[containerId] = keywords.split(",").map(tag => tag.trim());
    }
    
    // if (!tagData[containerId]) {
    //     tagData[containerId] = predefinedKeywords[keywordType] || [];
    // }

    tagContainer.addEventListener("keypress", function (event) {
        if (event.key === "Enter" && tagInput.value.trim() !== "") {
            event.preventDefault();
            addTag(containerId, tagInput.value.trim());
            tagInput.value = "";
            tagInput.focus();
        }
    });

    tagContainer.addEventListener("click", function (event) {
        if (event.target.classList.contains("iafwzcai-ai-settings-close")) {
            const tagText = event.target.getAttribute("data-tag");
            removeTag(containerId, tagText);
        }
    });

    renderTags(containerId);
}




function getTagsById(containerId) {
    const container = document.getElementById(containerId);
    if (!container) {
        return '';
    }

    const tags = container.querySelectorAll('.iafwzcai-ai-settings-tag');
    let tagValues = [];

    tags.forEach(tag => {
        const tagText = tag.textContent.replace('×', '').trim(); // Remove '×' and trim spaces
        tagValues.push(tagText);
    });

    return tagValues.join(', '); // Return comma-separated string
}
   
function iafwzcaiAiSettingsSubmitTags(action_key) {
    let keywords = [];
    let actionType = "";

    switch (action_key) {
        case 'Spam_Detection':
            keywords = getTagsById('iafwzcai-ai-spam-div');
            actionType = jQuery("#iafwzcai_spam_handling").val();
            break;
        case 'Email_Detection':
            keywords = getTagsById('iafwzcai-email-detection-div');
            actionType = jQuery("#iafwzcai_email_handling").val();
            break;
        case 'Email_Validation':
            keywords = getTagsById('iafwzcai-email-validation-div');
            actionType = jQuery("#iafwzcai_email_validation_handling").val();
            break;
        case 'Other_Detection':
            keywords = getTagsById('iafwzcai-other-detection-div');
            actionType = jQuery("#iafwzcai_other_handling").val();
            break;
        default:
            alert("Invalid action key.");
            return;
    }

    if (!keywords.length) {
        alert("Please enter at least one keyword.");
        return;
    }

    jQuery.ajax({
        url: iafwzcai_ai_settings.ajax_url,
        type: 'POST',
        data: {
            action: 'iafwzcai_ai_settings_request',
            keyword: keywords,
            action_type: actionType,
            action_key: action_key,
            security: iafwzcai_ai_settings.ai_settings_nonce
        },
        success: function (response) {
            if (response.success) {
                alert("Settings have been saved successfully!");
            } else {
                alert("An error occurred while saving the settings. Please try again.");
            }
        },
        error: function (xhr, status, error) {
            alert("An unexpected error occurred. Please check your internet connection and try again.");
        }
    });
}

        
function removeAllTags(containerId) {
    if (tagData[containerId]) {
        tagData[containerId] = []; // Clear tag array
        renderTags(containerId);
    }
}

function resetTags(containerId, keywordType) {
    if (predefinedKeywords[keywordType]) {
        tagData[containerId] = [...predefinedKeywords[keywordType]];
    } else {
        tagData[containerId] = [];
    }
    renderTags(containerId);
}

        
        