// ChessVIP PRO — Floating Settings Panel (injected into Chess.com)
// Replicates popup.html functionality: license activation, status, settings
console.log("[ChessVIP PRO] Settings panel script loaded");

(function () {
    "use strict";

    const BUILD_INFO = {
        version: '4.6.0',
        buildId: 'cvp-4.6-cloudflare-aware-20260508',
        channel: 'cloudflare-aware'
    };
    let panelEl = null;
    let miniEl = null;
    let isVisible = false;

    // ─────────────────────────────────────────────────────
    // HTML Template
    // ─────────────────────────────────────────────────────
    function getPanelHTML() {
        return `
        <div class="cvp-titlebar">
            <div class="cvp-title-text">
                <span class="cvp-logo">
                    <span class="cvp-logo-crown">♚</span>ChessVIP<span class="cvp-logo-pro">PRO</span>
                </span>
                <span class="cvp-version">v4.8</span>
            </div>
            <div class="cvp-controls">
                <button class="cvp-btn-minimize" title="Minimize">─</button>
                <button class="cvp-btn-close" title="Close">✕</button>
            </div>
        </div>
        <div class="cvp-body">
            <!-- Status Card -->
            <div class="cvp-glass-card">
                <div class="cvp-status-row">
                    <span class="cvp-status-label">Status:</span>
                    <span class="cvp-status-value" id="cvpStatusText">Not Activated</span>
                </div>
                <div class="cvp-status-row">
                    <span class="cvp-status-label">Plan:</span>
                    <span class="cvp-status-value" id="cvpPackageName">-</span>
                </div>
                <div class="cvp-status-row">
                    <span class="cvp-status-label">Expires:</span>
                    <span class="cvp-status-value" id="cvpExpiryDate">-</span>
                </div>
            </div>

            <!-- License Section -->
            <div class="cvp-glass-card" id="cvpLicenseSection">
                <div class="cvp-license-title">License Key</div>
                <input type="text" id="cvpLicenseInput" class="cvp-license-input" placeholder="XXXX-XXXX-XXXX-XXXX">
                <button id="cvpActivateBtn" class="cvp-btn-activate">Activate</button>
                <div style="margin-top:8px;padding:7px 10px;border-radius:8px;background:rgba(245,158,11,0.08);border:1px solid rgba(245,158,11,0.15);font-size:10px;color:rgba(245,158,11,0.85);line-height:1.5;text-align:center;">
                    ⚠️ Nhớ refresh lại trang Chess.com sau khi nhập key (F5)<br>
                    <span style="color:rgba(241,245,249,0.4);font-size:9px;">Remember to refresh Chess.com after entering your key</span>
                </div>
                <div id="cvpMessageBox" class="cvp-message"></div>
                <div id="cvpActivationSuccess" class="cvp-activation-success" aria-live="polite">
                    <div class="cvp-success-shine"></div>
                    <div class="cvp-success-kicker">ChessVIP Pro</div>
                    <div class="cvp-success-title">Thanks for supporting our products!</div>
                    <div class="cvp-success-subtitle">Your license is active. Refresh Chess.com once to start clean.</div>
                    <div class="cvp-success-support">Zalo: 0827858831</div>
                </div>
            </div>

            <!-- Expiry Info -->
            <div class="cvp-expiry-info" id="cvpExpiryInfo">
                <div class="cvp-expiry-days" id="cvpDaysLeft">30</div>
                <div class="cvp-expiry-label" id="cvpRemainingLabel">days remaining</div>
                <button id="cvpLogoutBtn" class="cvp-btn-logout">Log out</button>
            </div>

            <!-- Settings -->
            <div class="cvp-settings-section">
                <div class="cvp-settings-title">Display Options</div>
                <div class="cvp-setting-item">
                    <span class="cvp-setting-label">Show Arrows</span>
                    <label class="cvp-toggle">
                        <input type="checkbox" id="cvpShowArrows" checked>
                        <span class="cvp-toggle-slider"></span>
                    </label>
                </div>
                <div class="cvp-setting-item">
                    <span class="cvp-setting-label">Show Colored Squares</span>
                    <label class="cvp-toggle">
                        <input type="checkbox" id="cvpShowSquares" checked>
                        <span class="cvp-toggle-slider"></span>
                    </label>
                </div>
            </div>

            <!-- Footer -->
            <div class="cvp-footer">
                <p>Le Thanh Vinh — Chess VIP</p>
            </div>
        </div>`;
    }

    function normalizePanelText() {
        if (!panelEl) return;

        const logo = panelEl.querySelector(".cvp-logo-crown");
        if (logo) logo.innerHTML = "&#9818;";

        const minimize = panelEl.querySelector(".cvp-btn-minimize");
        if (minimize) minimize.innerHTML = "&minus;";

        const close = panelEl.querySelector(".cvp-btn-close");
        if (close) close.innerHTML = "&times;";

        const reminder = panelEl.querySelector("#cvpLicenseSection > div[style]");
        if (reminder) {
            reminder.innerHTML = `
                &#9888;&#65039; Nh&#7899; refresh l&#7841;i trang Chess.com sau khi nh&#7853;p key (F5)<br>
                <span style="color:rgba(241,245,249,0.4);font-size:9px;">Remember to refresh Chess.com after entering your key</span>
            `;
        }

        const footer = panelEl.querySelector(".cvp-footer p");
        if (footer) footer.innerHTML = "Le Thanh Vinh &mdash; Chess VIP";
    }

    // ─────────────────────────────────────────────────────
    // Create Panel + Mini Button
    // ─────────────────────────────────────────────────────
    function createPanel() {
        if (panelEl) return;

        panelEl = document.createElement("div");
        panelEl.id = "cvp-settings-panel";
        panelEl.innerHTML = getPanelHTML();
        normalizePanelText();
        document.body.appendChild(panelEl);

        miniEl = document.createElement("div");
        miniEl.id = "cvp-settings-mini";
        miniEl.innerHTML = "♚";
        miniEl.innerHTML = "&#9818;";
        miniEl.title = "Open ChessVIP Settings";
        document.body.appendChild(miniEl);

        // Restore saved position
        chrome.storage.local.get("cvpPanelPosition", (data) => {
            if (data.cvpPanelPosition) {
                const { x, y } = data.cvpPanelPosition;
                const maxX = window.innerWidth - 100;
                const maxY = window.innerHeight - 100;
                panelEl.style.left = Math.min(Math.max(0, x), maxX) + "px";
                panelEl.style.top = Math.min(Math.max(0, y), maxY) + "px";
            }
        });

        setupDrag();
        setupControls();
        setupLicense();
        setupSettings();
    }

    // ─────────────────────────────────────────────────────
    // Drag & Drop
    // ─────────────────────────────────────────────────────
    function setupDrag() {
        const titlebar = panelEl.querySelector(".cvp-titlebar");
        let isDragging = false;
        let offsetX = 0, offsetY = 0;

        titlebar.addEventListener("mousedown", (e) => {
            if (e.target.closest("button")) return;
            isDragging = true;
            offsetX = e.clientX - panelEl.getBoundingClientRect().left;
            offsetY = e.clientY - panelEl.getBoundingClientRect().top;
            panelEl.style.transition = "none";
            e.preventDefault();
        });

        document.addEventListener("mousemove", (e) => {
            if (!isDragging) return;
            const x = Math.max(0, Math.min(e.clientX - offsetX, window.innerWidth - panelEl.offsetWidth));
            const y = Math.max(0, Math.min(e.clientY - offsetY, window.innerHeight - 40));
            panelEl.style.left = x + "px";
            panelEl.style.top = y + "px";
        });

        document.addEventListener("mouseup", () => {
            if (!isDragging) return;
            isDragging = false;
            panelEl.style.transition = "";
            chrome.storage.local.set({
                cvpPanelPosition: {
                    x: parseInt(panelEl.style.left),
                    y: parseInt(panelEl.style.top)
                }
            });
        });
    }

    // ─────────────────────────────────────────────────────
    // Minimize / Close Controls
    // ─────────────────────────────────────────────────────
    function setupControls() {
        panelEl.querySelector(".cvp-btn-minimize").addEventListener("click", minimizePanel);
        panelEl.querySelector(".cvp-btn-close").addEventListener("click", hidePanel);
        miniEl.addEventListener("click", () => {
            miniEl.classList.remove("cvp-mini-visible");
            showPanel();
        });
    }

    function showPanel() {
        createPanel();
        panelEl.style.display = "flex";
        panelEl.classList.remove("cvp-hide");
        panelEl.classList.add("cvp-show");
        isVisible = true;
    }

    function hidePanel() {
        if (!panelEl) return;
        panelEl.classList.remove("cvp-show");
        panelEl.classList.add("cvp-hide");
        setTimeout(() => { panelEl.style.display = "none"; }, 200);
        isVisible = false;
    }

    function minimizePanel() {
        hidePanel();
        miniEl.classList.add("cvp-mini-visible");
    }

    function togglePanel() {
        if (!panelEl || panelEl.style.display === "none" || !isVisible) {
            if (miniEl) miniEl.classList.remove("cvp-mini-visible");
            showPanel();
        } else {
            hidePanel();
        }
    }

    // ─────────────────────────────────────────────────────
    // License Logic (replicated from popup.js)
    // ─────────────────────────────────────────────────────
    function setupLicense() {
        const keyInput = panelEl.querySelector("#cvpLicenseInput");
        const activateBtn = panelEl.querySelector("#cvpActivateBtn");
        const statusEl = panelEl.querySelector("#cvpStatusText");
        const planEl = panelEl.querySelector("#cvpPackageName");
        const expiryEl = panelEl.querySelector("#cvpExpiryDate");
        const daysEl = panelEl.querySelector("#cvpDaysLeft");
        const remainingLabel = panelEl.querySelector("#cvpRemainingLabel");
        const expiryInfo = panelEl.querySelector("#cvpExpiryInfo");
        const messageBox = panelEl.querySelector("#cvpMessageBox");
        const activationSuccess = panelEl.querySelector("#cvpActivationSuccess");
        const logoutBtn = panelEl.querySelector("#cvpLogoutBtn");

        function showMessage(text, isError) {
            messageBox.textContent = text;
            messageBox.className = 'cvp-message ' + (isError ? 'error' : 'success');
            messageBox.style.display = 'block';
            setTimeout(() => { messageBox.style.display = 'none'; }, 3000);
        }

        function showPremiumActivationEffect(plan, expireAt) {
            if (!activationSuccess) return;
            const subtitle = activationSuccess.querySelector(".cvp-success-subtitle");
            if (subtitle) {
                const expText = expireAt ? new Date(expireAt).toLocaleDateString('en-US') : '';
                subtitle.textContent = expText
                    ? `Your ${plan || 'VIP'} license is active until ${expText}. Refresh Chess.com once to start clean.`
                    : `Your ${plan || 'VIP'} license is active. Refresh Chess.com once to start clean.`;
            }
            activationSuccess.classList.remove("cvp-success-visible");
            void activationSuccess.offsetWidth;
            activationSuccess.classList.add("cvp-success-visible");
            setTimeout(() => {
                activationSuccess?.classList.remove("cvp-success-visible");
            }, 6500);
        }

        function getLicenseErrorMessage(errorCode) {
            const messages = {
                LICENSE_NOT_FOUND: 'License key not found.',
                LICENSE_DISABLED: 'This license key is disabled.',
                LICENSE_EXPIRED: 'This license key has expired.',
                LICENSE_REVOKED: 'This license key has been revoked.',
                KEY_EXPIRED: 'This license key has expired.',
                INVALID_KEY: 'Invalid license key.',
                DEVICE_MISMATCH: 'This key is already active on another device.',
                RATE_LIMITED: 'Too many requests. Please wait a moment.',
                KEY_RATE_LIMITED: 'This key is temporarily locked due to repeated attempts.',
                KEY_ALREADY_ACTIVATED: 'This key is already active on another device.',
                SERVER_ERROR: 'Server error. Please try again later.',
                SERVER_CONFIG_ERROR: 'Server configuration error.'
            };
            return messages[errorCode] || `Error: ${errorCode || 'Unknown'}`;
        }

        function sendBackgroundMessage(message) {
            return new Promise((resolve) => {
                try {
                    chrome.runtime.sendMessage(message, (response) => {
                        if (chrome.runtime.lastError) {
                            resolve({ valid: false, error: chrome.runtime.lastError.message });
                            return;
                        }
                        resolve(response || { valid: false, error: 'NO_RESPONSE' });
                    });
                } catch (e) {
                    resolve({ valid: false, error: e.message || 'BACKGROUND_ERROR' });
                }
            });
        }

        async function checkAndRefreshToken() {
            const state = await sendBackgroundMessage({ action: 'license:getState', force: true });
            if (state?.rateLimited) {
                showMessage('Too many requests. Try again after ' + (state.retryAfter || 30) + 's', true);
            }
            return state?.valid ? state : false;
        }

        async function validateLicense(licenseKey, deviceId) {
            return await sendBackgroundMessage({ action: 'license:activate', licenseKey });
        }

        function showInactive() {
            statusEl.textContent = 'Not Activated';
            statusEl.className = 'cvp-status-value cvp-status-inactive';
            planEl.textContent = '-';
            expiryEl.textContent = '-';
            expiryInfo.style.display = 'none';
            keyInput.disabled = false;
            activateBtn.disabled = false;
            activateBtn.textContent = 'Activate';
        }

        function showActive(expireAt, plan, key) {
            statusEl.textContent = 'Activated';
            statusEl.className = 'cvp-status-value cvp-status-active';

            const planNames = {
                'lifetime': 'Lifetime', '365d': 'VIP (1 Year)', '180d': '180 Days',
                '90d': '90 Days', '30d': 'Pro (30 Days)', '7d': '7 Days', '1d': '1 Day', 'VIP': 'VIP'
            };
            let displayPlan = planNames[plan];
            if (!displayPlan && plan && plan.endsWith('h')) {
                const hours = parseInt(plan);
                displayPlan = hours + ' Hour' + (hours > 1 ? 's' : '');
            }
            planEl.textContent = displayPlan || plan || 'VIP';

            const now = Date.now();
            const msLeft = expireAt - now;
            const rawHoursLeft = msLeft / (60 * 60 * 1000);
            const rawDaysLeft = msLeft / (24 * 60 * 60 * 1000);
            const hoursLeft = Math.max(0, Math.ceil(rawHoursLeft));
            const daysLeftVal = Math.max(0, Math.ceil(rawDaysLeft));
            const expDate = new Date(expireAt);

            if (rawHoursLeft < 24) {
                expiryEl.textContent = expDate.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
                daysEl.textContent = hoursLeft > 0 ? hoursLeft : '0';
                if (remainingLabel) remainingLabel.textContent = 'hours remaining';
            } else {
                expiryEl.textContent = expDate.toLocaleDateString('en-US');
                daysEl.textContent = daysLeftVal > 0 ? daysLeftVal : 0;
                if (remainingLabel) remainingLabel.textContent = 'days remaining';
            }

            // Color coding
            if (rawDaysLeft <= 1) {
                expiryInfo.style.background = 'linear-gradient(135deg, #ef444420, #dc262620)';
                expiryInfo.style.borderColor = '#ef444440';
                daysEl.style.color = '#ef4444';
            } else if (rawDaysLeft <= 3) {
                expiryInfo.style.background = 'linear-gradient(135deg, #f9731620, #ea580c20)';
                expiryInfo.style.borderColor = '#f9731640';
                daysEl.style.color = '#f97316';
            } else {
                expiryInfo.style.background = 'linear-gradient(135deg, #22c55e20, #16a34a20)';
                expiryInfo.style.borderColor = '#22c55e40';
                daysEl.style.color = '#4ade80';
            }

            expiryInfo.style.display = 'block';
            keyInput.value = key || '';
            keyInput.disabled = true;
            activateBtn.disabled = true;
            activateBtn.textContent = 'Activated';
        }

        async function updateUI() {
            const stored = await chrome.storage.local.get(['token', 'licenseKey', 'expire_at', 'plan']);
            if (!stored.token && !stored.licenseKey) { showInactive(); return; }
            const refreshResult = await checkAndRefreshToken();
            if (!refreshResult || !refreshResult.valid) {
                if (refreshResult === false) showInactive();
                return;
            }
            const updated = await chrome.storage.local.get(['expire_at', 'plan', 'licenseKey']);
            showActive(updated.expire_at || refreshResult.expire_at, updated.plan || 'VIP', updated.licenseKey);
        }

        // Activate button
        activateBtn.addEventListener('click', async () => {
            const key = keyInput.value.trim().toUpperCase();
            if (!key) { showMessage('Please enter a License Key', true); return; }
            activateBtn.disabled = true;
            activateBtn.textContent = 'Processing...';
            try {
                const data = await sendBackgroundMessage({ action: 'license:activate', licenseKey: key });

                if (data.rateLimited || data.error === 'RATE_LIMITED') {
                    showMessage('Too many requests. Try again after ' + (data.retryAfter || 30) + 's', true);
                    activateBtn.disabled = false;
                    activateBtn.textContent = 'Activate';
                    return;
                }

                if (data.valid) {
                    showActive(data.expire_at, data.plan || 'VIP', key);
                    showMessage('Activation successful!', false);
                    showPremiumActivationEffect(data.plan || 'VIP', data.expire_at);
                } else {
                    showMessage(getLicenseErrorMessage(data.error), true);
                    activateBtn.disabled = false;
                    activateBtn.textContent = 'Activate';
                    return;
                    const errors = {
                        'LICENSE_NOT_FOUND': 'Key not found!',
                        'LICENSE_DISABLED': 'Key đã bị vô hiệu hóa!',
                        'LICENSE_EXPIRED': 'Key đã hết hạn!',
                        'LICENSE_REVOKED': 'Key đã bị thu hồi!',
                        'KEY_EXPIRED': 'Key đã hết hạn!',
                        'INVALID_KEY': 'Invalid key!',
                        'DEVICE_MISMATCH': 'Key activated on another device!',
                        'RATE_LIMITED': 'Quá nhiều yêu cầu, vui lòng đợi.',
                        'KEY_RATE_LIMITED': 'Key tạm khóa do spam.',
                        'KEY_ALREADY_ACTIVATED': 'Key already activated on another device!',
                        'SERVER_ERROR': 'Lỗi server, thử lại sau.',
                        'SERVER_CONFIG_ERROR': 'Lỗi cấu hình server.'
                    };
                    showMessage(errors[data.error] || 'Error: ' + (data.error || 'Unknown'), true);
                    activateBtn.disabled = false;
                    activateBtn.textContent = 'Activate';
                }
            } catch (e) {
                showMessage('Server connection error!', true);
                activateBtn.disabled = false;
                activateBtn.textContent = 'Activate';
            }
        });

        // Logout
        logoutBtn.addEventListener('click', async () => {
            if (!confirm('Are you sure you want to log out? The license key will be removed.')) return;
            await sendBackgroundMessage({ action: 'license:logout' });
            showInactive();
            showMessage('Logged out successfully!', false);
            return;
            if (!confirm('Bạn có chắc muốn đăng xuất? License key sẽ bị xóa.')) return;
            await sendBackgroundMessage({ action: 'license:logout' });
            showInactive();
            showMessage('Logged out successfully!', false);
        });

        // Init
        updateUI();
    }

    // ─────────────────────────────────────────────────────
    // Settings (Arrows / Squares toggles)
    // ─────────────────────────────────────────────────────
    function setupSettings() {
        const arrowsToggle = panelEl.querySelector("#cvpShowArrows");
        const squaresToggle = panelEl.querySelector("#cvpShowSquares");

        function sendSettingsMessage(message) {
            return new Promise((resolve) => {
                try {
                    chrome.runtime.sendMessage(message, (response) => {
                        if (chrome.runtime.lastError) {
                            resolve({ ok: false, error: chrome.runtime.lastError.message });
                            return;
                        }
                        resolve(response || { ok: false, error: 'NO_RESPONSE' });
                    });
                } catch (e) {
                    resolve({ ok: false, error: e.message || 'SETTINGS_ERROR' });
                }
            });
        }

        function applySettings(settings = {}) {
            if (arrowsToggle) arrowsToggle.checked = settings.showArrows !== false;
            if (squaresToggle) squaresToggle.checked = settings.showSquares !== false;
        }

        sendSettingsMessage({ action: 'settings:get' }).then(response => {
            applySettings(response.settings || {});
        });

        arrowsToggle?.addEventListener('change', async (e) => {
            const response = await sendSettingsMessage({
                action: 'settings:set',
                settings: { showArrows: e.target.checked }
            });
            if (response.settings) applySettings(response.settings);
        });

        squaresToggle?.addEventListener('change', async (e) => {
            const response = await sendSettingsMessage({
                action: 'settings:set',
                settings: { showSquares: e.target.checked }
            });
            if (response.settings) applySettings(response.settings);
        });
    }

    // ─────────────────────────────────────────────────────
    // Listen for toggle message from background.js
    // ─────────────────────────────────────────────────────
    chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
        console.log("[ChessVIP PRO] Panel message received:", msg);
        if (msg && msg.action === "togglePanel") {
            togglePanel();
            sendResponse({ ok: true });
        }
    });

    console.log("[ChessVIP PRO] Settings panel listener registered.");

})();
