// ============================================================================
// MEMBERSHIP GATE
// Plans with access: Trial (active), Novice, Professional, Prestige.
// Same three-layer pattern used across all gated pages:
//   _trackerUid absence → logged out, reject immediately.
//   background checkMembership → { allowed } boolean.
//   _cachedPlan → fallback when background auth is unavailable.
// ============================================================================

const TRACKER_ALLOWED_PLANS = ['trial', 'novice', 'professional', 'prestige'];

async function verifyTrackerAccess() {
    const { _trackerUid } = await chrome.storage.local.get('_trackerUid');
    if (!_trackerUid) {
        showTrackerGateModal('none', null);
        return false;
    }

    const result = await new Promise(resolve => {
        chrome.runtime.sendMessage({ type: 'checkMembership' }, res => {
            void chrome.runtime.lastError;
            resolve(res || null);
        });
    });

    if (result?.allowed === true) return true;

    const { _cachedPlan } = await chrome.storage.local.get('_cachedPlan');
    if (_cachedPlan && TRACKER_ALLOWED_PLANS.includes(_cachedPlan.toLowerCase().trim())) {
        return true;
    }

    showTrackerGateModal(result?.membership ?? null, _cachedPlan ?? null);
    return false;
}

function showTrackerGateModal(membership, cachedPlan) {
    const existing = document.getElementById('ss-tracker-gate-modal');
    if (existing) existing.remove();

    let bodyText;
    if (membership === 'expired') {
        bodyText = 'Your membership has <strong style="color:#f87171">expired</strong>. Please renew to continue using the Tracker.';
    } else if (cachedPlan && !TRACKER_ALLOWED_PLANS.includes(cachedPlan.toLowerCase().trim())) {
        bodyText = `Your current plan <strong style="color:#f87171">${cachedPlan}</strong> does not have Tracker access.`;
    } else {
        bodyText = 'No active membership was found. Please log in through the website.';
    }

    const overlay = document.createElement('div');
    overlay.id = 'ss-tracker-gate-modal';
    overlay.style.cssText = [
        'position:fixed', 'inset:0', 'z-index:99999',
        'background:rgba(0,0,0,0.65)', 'backdrop-filter:blur(4px)',
        'display:flex', 'align-items:center', 'justify-content:center',
    ].join(';');

    overlay.innerHTML = `
        <div style="background:#0f1624;border:1px solid #2a3a5c;border-radius:16px;
                    padding:44px 48px;max-width:480px;width:90%;text-align:center;
                    box-shadow:0 12px 60px rgba(0,0,0,0.7);">
            <div style="font-size:52px;margin-bottom:18px;">🔒</div>
            <h2 style="color:#e2e8f0;font-size:22px;margin:0 0 12px 0;font-weight:700;">Access Restricted</h2>
            <p style="color:#94a3b8;font-size:15px;margin:0 0 20px 0;line-height:1.7;">
                ${bodyText}
            </p>
            <p style="color:#64748b;font-size:13px;margin:0 0 28px 0;line-height:1.6;">
                Eligible plans:<br>
                Trial &nbsp;·&nbsp; Novice &nbsp;·&nbsp; Professional &nbsp;·&nbsp; Prestige
            </p>
            <button id="ss-tracker-gate-close"
                style="background:#1e3a5f;color:#e2e8f0;border:1px solid #2a4a7f;
                       border-radius:8px;padding:12px 36px;cursor:pointer;font-size:15px;font-weight:600;">
                Close
            </button>
        </div>`;

    document.body.appendChild(overlay);
    document.getElementById('ss-tracker-gate-close').addEventListener('click', () => overlay.remove());
    overlay.addEventListener('click', e => { if (e.target === overlay) overlay.remove(); });
}

// ─── Settings Groups (multi-field: checkboxes + selects) ────────────────────

const settingsGroups = [
    {
        elementId: 'enable_stock_monitor',
        storageKey: 'enable_stock_monitor',
        defaultValue: { checkbox: false, prime_option: 'prime_only', restock_quantity: 1 }
    },
    {
        elementId: 'enable_price_monitor',
        storageKey: 'enable_price_monitor',
        defaultValue: { checkbox: false, pricing_option: 'markup_pricing', markup_percentage: 100, price_trigger_threshold: 2 }
    },
    {
        elementId: 'enable_price_ending_filter',
        storageKey: 'enable_price_ending_filter',
        defaultValue: { checkbox: false, price_endings: '99, 97, 95' }
    },
    {
        elementId: 'enable_delete_policy_violation_items',
        storageKey: 'enable_delete_policy_violation_items',
        defaultValue: { checkbox: false }
    },
    {
        elementId: 'enable_delete_items_with_no_sku',
        storageKey: 'enable_delete_items_with_no_sku',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_delete_items_not_found_on_amazon',
        storageKey: 'enable_delete_items_not_found_on_amazon',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_delete_items_sku_changed_on_amazon',
        storageKey: 'enable_delete_items_sku_changed_on_amazon',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_delete_items_with_no_sales',
        storageKey: 'enable_delete_items_with_no_sales',
        defaultValue: { checkbox: false, action: 'delete', sales_threshold: 0, days_threshold: 30 }
    },
    {
        elementId: 'enable_delete_items_with_broken_sku',
        storageKey: 'enable_delete_items_with_broken_sku',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_delete_items_by_non_chinese_sellers',
        storageKey: 'enable_delete_items_by_non_chinese_sellers',
        defaultValue: { checkbox: false, action: 'delete' }
    },
    {
        elementId: 'enable_set_gspr',
        storageKey: 'enable_set_gspr',
        defaultValue: { checkbox: false }
    },
    {
        elementId: 'enable_set_skus_to_items',
        storageKey: 'enable_set_skus_to_items',
        defaultValue: { checkbox: false }
    },
    {
        elementId: 'enable_scan_for_restricted_words',
        storageKey: 'enable_scan_for_restricted_words',
        defaultValue: { checkbox: false }
    },
    {
        elementId: 'force_restock_quantity_setting',
        storageKey: 'force_restock_quantity_setting',
        defaultValue: { checkbox: false, restock_quantity: 3 }
    }
];

// For each settings group, bind all inputs/selects to chrome.storage and restore saved values
settingsGroups.forEach(function (group) {
    const container = document.getElementById(group.elementId);
    if (!container) {
        console.error('Container with id ' + group.elementId + ' not found');
        return;
    }

    const inputs = container.querySelectorAll('input, select');

    function saveGroupToStorage() {
        const values = {};
        inputs.forEach(function (input) {
            const name = input.name;
            if (name) {
                values[name] = input.type === 'checkbox' ? input.checked : input.value;
            }
        });
        chrome.storage.local.set({ [group.storageKey]: values });
        console.log(group.storageKey + ':', values);
    }

    // Listen for changes on each input/select
    inputs.forEach(function (input) {
        const eventType = (input.type === 'checkbox' || input.tagName.toLowerCase() === 'select') ? 'change' : 'input';
        input.addEventListener(eventType, saveGroupToStorage);
    });

    // Restore saved values (or write defaults if not set)
    chrome.storage.local.get(group.storageKey, function (stored) {
        let values = stored[group.storageKey];
        if (values === undefined) {
            values = group.defaultValue;
            chrome.storage.local.set({ [group.storageKey]: values });
        }
        inputs.forEach(function (input) {
            const name = input.name;
            if (name && values.hasOwnProperty(name)) {
                if (input.type === 'checkbox') {
                    input.checked = values[name];
                } else {
                    input.value = values[name];
                }
            }
        });
        console.log(group.storageKey + ':', values);
    });
});


// ─── Simple Settings (single checkbox or input per key) ─────────────────────

const simpleSettings = [
    { elementId: 'tracker_run_status', storageKey: 'tracker_run_status', defaultValue: false, type: 'checkbox', event: 'change' },
    { elementId: 'enable_continuous_tracking', storageKey: 'enable_continuous_tracking', defaultValue: false, type: 'checkbox', event: 'click' },
    { elementId: 'tracking_timeout', storageKey: 'tracking_timeout', defaultValue: 60, type: 'input', event: 'input' },
    { elementId: 'page_number', storageKey: 'page_number', defaultValue: 1, type: 'input', event: 'input' },
    { elementId: 'current_tracker_position', storageKey: 'current_tracker_position', defaultValue: 1, type: 'input', event: 'input' },
    { elementId: 'should_track_log', storageKey: 'should_track_log', defaultValue: false, type: 'checkbox', event: 'change' },
    { elementId: 'should_pin_tabs', storageKey: 'should_pin_tabs', defaultValue: false, type: 'checkbox', event: 'change' },
    { elementId: 'stay_on_ebay_page', storageKey: 'stay_on_ebay_page', defaultValue: false, type: 'checkbox', event: 'change' },
    { elementId: 'force_domain', storageKey: 'force_domain', defaultValue: false, type: 'checkbox', event: 'change' }
];

simpleSettings.forEach(function (setting) {
    console.log(setting);
    const el = document.getElementById(setting.elementId);

    el.addEventListener(setting.event, function () {
        const value = setting.type === 'checkbox' ? el.checked : el.value;
        chrome.storage.local.set({ [setting.storageKey]: value });
        console.log(setting.storageKey + ':', value);
    });

    chrome.storage.local.get(setting.storageKey, function (stored) {
        let value = stored[setting.storageKey];
        if (value === undefined) {
            value = setting.defaultValue;
            chrome.storage.local.set({ [setting.storageKey]: value });
        }
        if (setting.type === 'checkbox') {
            el.checked = value;
        } else {
            el.value = value;
        }
        console.log(setting.storageKey + ':', value);
    });
});


// ─── Start Tracking Button ───────────────────────────────────────────────────

document.getElementById('start_tracking').addEventListener('click', async function () {
    console.log('Sending message to background.js to start tracking');
    document.getElementById('tracker_run_status').checked = true;

    const filterCheckboxes = document.getElementById('tracker_filters').querySelectorAll('input[type="checkbox"]');
    let anyChecked = false;
    for (let i = 0; i < filterCheckboxes.length; i++) {
        if (filterCheckboxes[i].checked) {
            anyChecked = true;
            break;
        }
    }

    if (anyChecked) {
        // ── Membership gate ────────────────────────────────────────
        const hasAccess = await verifyTrackerAccess();
        if (!hasAccess) {
            document.getElementById('tracker_run_status').checked = false;
            chrome.storage.local.set({ tracker_run_status: false });
            return;
        }
        // ────────────────────────────────────────────────
        chrome.storage.local.set({ tracker_run_status: true });
        chrome.runtime.sendMessage({ type: 'start_tracking' });
    } else {
        alert('Please select at least one filter to track');
        document.getElementById('tracker_run_status').checked = false;
        chrome.storage.local.set({ tracker_run_status: false });
    }
});


// ─── Test Button ─────────────────────────────────────────────────────────────

document.getElementById('test_button').addEventListener('click', async function () {
    console.log('Sending message to background.js to test item');
    const itemNumber = document.getElementById('test_button_value').value;
    chrome.storage.local.set({ test_button_value: itemNumber });

    const { response } = await new Promise(resolve => {
        chrome.runtime.sendMessage({ type: 'track_single_item', itemNumber }, resolve);
    });
    console.log('response', response);
});


// ─── Open Logs Button ────────────────────────────────────────────────────────

document.getElementById('open_logs').addEventListener('click', async function (e) {
    const { tracking_log } = await chrome.storage.local.get('tracking_log');
    console.log('tracking_log', tracking_log);
    e.preventDefault();
    chrome.tabs.create({ url: chrome.runtime.getURL('Stock_Monitor_Repricer/tracking_logs/index.html') });
});


// ─── Toggle Hidden Filters Menu ──────────────────────────────────────────────

document.getElementById('tracking_filters_title').addEventListener('click', function () {
    document.querySelectorAll('.hidden_menu').forEach(function (menu) {
        menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
    });
});


// ─── Non-Chinese Sellers: Print & Clear ──────────────────────────────────────

document.getElementById('print_non_chinese_sellers_item_ids').addEventListener('click', async function () {
    const { nonChineseSellerItemIds } = await chrome.storage.local.get('nonChineseSellerItemIds');
    console.log('nonChineseSellerItemIds', nonChineseSellerItemIds);

    if (nonChineseSellerItemIds && nonChineseSellerItemIds.length !== 0) {
        const text = nonChineseSellerItemIds.join('\n');
        const blob = new Blob([text], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'non_chinese_sellers_item_ids.txt';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        alert('Item IDs have been saved to a text file');
    } else {
        alert('No non-Chinese seller item IDs found');
    }
});

document.getElementById('clear_non_chinese_sellers_item_ids').addEventListener('click', async function () {
    await chrome.storage.local.remove('nonChineseSellerItemIds');
    alert('Non-Chinese seller item IDs have been cleared');
});


// ─── Failed GSPR Items: Print & Clear ────────────────────────────────────────

document.getElementById('print_failed_gspr_items').addEventListener('click', async function () {
    const { failedGsprItems } = await chrome.storage.local.get('failedGsprItems');
    console.log('failedGsprItems', failedGsprItems);

    if (failedGsprItems && failedGsprItems.length !== 0) {
        const text = failedGsprItems.join('\n');
        const blob = new Blob([text], { type: 'text/plain' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'failed_gspr_items.txt';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        alert('Failed GSPR items have been saved to a text file');
    } else {
        alert('No failed GSPR items found');
    }
});

document.getElementById('clear_failed_gspr_items').addEventListener('click', async function () {
    await chrome.storage.local.remove('failedGsprItems');
    alert('Failed GSPR items have been cleared');
    document.getElementById('total_failed_gspr_items').innerText = 0;
    document.getElementById('gspr_item_numbers').value = '';
});


// ─── Init UI State ───────────────────────────────────────────────────────────

async function initUI() {
    // Restore test button value
    const { test_button_value } = await chrome.storage.local.get('test_button_value');
    console.log('test_button_value', test_button_value);
    if (test_button_value) {
        document.getElementById('test_button_value').value = test_button_value;
    }
    document.getElementById('test_button_value').addEventListener('input', function () {
        console.log('test_button_value input event');
        const value = document.getElementById('test_button_value').value;
        chrome.storage.local.set({ test_button_value: value });
    });

    // Restore markup percentage
    const { markupPrice } = await chrome.storage.local.get('markupPrice');
    console.log('markupPrice', markupPrice);
    document.querySelector('input[name="markup_percentage"]').value = markupPrice;
    document.querySelector('input[name="markup_percentage"]').addEventListener('input', function () {
        console.log('markup_percentage input event');
        const value = document.querySelector('input[name="markup_percentage"]').value;
        chrome.storage.local.set({ markupPrice: value });
    });

    // Restore total page number
    let { totalPageNumber } = await chrome.storage.local.get('totalPageNumber');
    if (!totalPageNumber) totalPageNumber = 1;
    document.getElementById('totalPageNumber').innerText = totalPageNumber;

    // Restore current tracker position
    let { current_tracker_position } = await chrome.storage.local.get('current_tracker_position');
    if (!current_tracker_position) current_tracker_position = 1;
    document.getElementById('current_tracker_position').value = current_tracker_position;

    // Restore failed GSPR items display
    chrome.storage.local.get('failedGsprItems', function ({ failedGsprItems }) {
        if (failedGsprItems && failedGsprItems.length > 0) {
            document.getElementById('gspr_item_numbers').value = failedGsprItems.join('\n');
            document.getElementById('total_failed_gspr_items').innerText = failedGsprItems.length;
        }
    });

    // ── Membership gate on open ────────────────────────
    verifyTrackerAccess();
    // ────────────────────────────────────────────────
}

initUI();


// ─── Message Listener: Update Tracker Progress UI ────────────────────────────

chrome.runtime.onMessage.addListener(function (message) {
    if (message.type !== 'update_tracker_position') return;

    const { page_number, total_pages, position_in_page, total_items_in_page } = message;

    // Item progress
    const itemPct = total_items_in_page > 0 ? Math.min(Math.max(position_in_page / total_items_in_page * 100, 0), 100) : 0;
    document.getElementById('current_item_label').textContent = position_in_page;
    document.getElementById('total_item_label').textContent = total_items_in_page;
    document.getElementById('item_percentage_label').textContent = itemPct.toFixed(0) + '%';
    document.getElementById('item_progress_fill').style.width = itemPct + '%';

    // Page progress
    const pagePct = total_pages > 0 ? Math.min(Math.max(page_number / total_pages * 100, 0), 100) : 0;
    document.getElementById('current_page_label').textContent = page_number;
    document.getElementById('total_page_label').textContent = total_pages;
    document.getElementById('page_percentage_label').textContent = pagePct.toFixed(0) + '%';
    document.getElementById('page_progress_fill').style.width = pagePct + '%';

    // Sync inputs
    document.getElementById('current_tracker_position').value = position_in_page;
    document.getElementById('totalPageNumber').innerText = total_pages;
    document.getElementById('page_number').value = page_number;

    // Update failed GSPR display
    chrome.storage.local.get('failedGsprItems', function ({ failedGsprItems }) {
        if (failedGsprItems && failedGsprItems.length > 0) {
            document.getElementById('gspr_item_numbers').value = failedGsprItems.join('\n');
            document.getElementById('total_failed_gspr_items').innerText = failedGsprItems.length;
        }
    });
});


// ─── Reset Tracking Button ───────────────────────────────────────────────────

document.getElementById('reset_tracking').addEventListener('click', function () {
    document.getElementById('current_tracker_position').value = 1;
    document.getElementById('page_number').value = 1;
    chrome.storage.local.set({ current_tracker_position: 1, page_number: 1 });
});



